From a72181a0ceab01c0e17c0fa1fb0f6a1bdd1ea2bc Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Fri, 20 Nov 2026 19:10:41 +0300 Subject: [PATCH 1/5] docs: add Triangle Media project handbook --- README.md | 6 +- README.ru.md | 4 +- public/llms.txt | 1 + public/sitemap.xml | 80 +++++++++++++++++++ src/components/Header.jsx | 1 + src/components/Logo.jsx | 4 +- src/components/Navigation.jsx | 24 +++++- src/pages/_app.jsx | 42 +++++++++- src/pages/api-ref/connection.mdx | 4 +- src/pages/api-ref/server.mdx | 2 +- src/pages/api-ref/timer.mdx | 2 +- src/pages/current/security.mdx | 2 +- src/pages/index.mdx | 8 +- src/pages/projects/media.mdx | 48 +++++++++++ src/pages/projects/media/compatibility.mdx | 29 +++++++ src/pages/projects/media/configuration.mdx | 54 +++++++++++++ src/pages/projects/media/en.mdx | 48 +++++++++++ src/pages/projects/media/en/compatibility.mdx | 29 +++++++ src/pages/projects/media/en/configuration.mdx | 54 +++++++++++++ src/pages/projects/media/en/processing.mdx | 35 ++++++++ src/pages/projects/media/en/security.mdx | 32 ++++++++ src/pages/projects/media/en/start.mdx | 66 +++++++++++++++ src/pages/projects/media/en/testing.mdx | 18 +++++ src/pages/projects/media/en/upload.mdx | 67 ++++++++++++++++ src/pages/projects/media/processing.mdx | 35 ++++++++ src/pages/projects/media/security.mdx | 32 ++++++++ src/pages/projects/media/start.mdx | 66 +++++++++++++++ src/pages/projects/media/testing.mdx | 18 +++++ src/pages/projects/media/upload.mdx | 67 ++++++++++++++++ 29 files changed, 860 insertions(+), 18 deletions(-) create mode 100644 src/pages/projects/media.mdx create mode 100644 src/pages/projects/media/compatibility.mdx create mode 100644 src/pages/projects/media/configuration.mdx create mode 100644 src/pages/projects/media/en.mdx create mode 100644 src/pages/projects/media/en/compatibility.mdx create mode 100644 src/pages/projects/media/en/configuration.mdx create mode 100644 src/pages/projects/media/en/processing.mdx create mode 100644 src/pages/projects/media/en/security.mdx create mode 100644 src/pages/projects/media/en/start.mdx create mode 100644 src/pages/projects/media/en/testing.mdx create mode 100644 src/pages/projects/media/en/upload.mdx create mode 100644 src/pages/projects/media/processing.mdx create mode 100644 src/pages/projects/media/security.mdx create mode 100644 src/pages/projects/media/start.mdx create mode 100644 src/pages/projects/media/testing.mdx create mode 100644 src/pages/projects/media/upload.mdx diff --git a/README.md b/README.md index 06c61b7..7cc4ea0 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,11 @@ Open http://localhost:3000 during development. Build output is `out/`; the postb ## Documentation scope -The Server handbook describes the current stable release, 7.1.0. The project switcher also provides separate documentation areas for Cluster, Cron, HTTP Client, MQTT, PSR-7, Proxy, SOCKS5, Socket.IO, Storage, Tunnel and Noter. Each area has its own sidebar, search results, project metadata and compatibility notes. +The Server handbook describes the current stable release, 7.2.0. The project switcher also provides separate documentation areas for Cluster, Cron, HTTP Client, MQTT, PSR-7, Proxy, SOCKS5, Socket.IO, Storage, Tunnel, Noter, and Triangle Media. Each area has its own sidebar, search results, project metadata and compatibility notes. Media documents the published v1.1.0 Engine 8 package separately from the prepared but unreleased 2.0.0 Engine 9 migration. -Older pages remain in the archive, carry an archive notice, and are excluded from the search index and sitemap. The site is primarily Russian and is not fully bilingual. Related-project pages reflect the checked out source and Composer lock state; they do not imply production readiness or unverified runtime behavior. +The AI-readable project map is available at [`public/llms.txt`](public/llms.txt); public pages are indexed in `public/sitemap.xml` and `public/robots.txt`. + +Older pages remain in the archive, carry an archive notice, and are excluded from the search index and sitemap. The Server handbook is primarily Russian; selected related-project guides are available in English and Russian. Related-project pages reflect checked out sources and verified release status; they do not imply production readiness or unverified runtime behavior. ## Source layout diff --git a/README.ru.md b/README.ru.md index fab7776..bc0baca 100644 --- a/README.ru.md +++ b/README.ru.md @@ -19,9 +19,9 @@ Dev-сайт открывается на http://localhost:3000. Результа ## Границы документации -Справочник Server описывает актуальный стабильный выпуск 7.1.0. Переключатель проектов открывает отдельную документацию Cluster, Cron, HTTP Client, MQTT, PSR-7, Proxy, SOCKS5, Socket.IO, Storage, Tunnel и Noter. Для каждого проекта выделены собственная боковая навигация, поиск, метаданные и сведения о совместимости. +Справочник Server описывает актуальный стабильный выпуск 7.2.0. Переключатель проектов открывает отдельную документацию Cluster, Cron, HTTP Client, MQTT, PSR-7, Proxy, SOCKS5, Socket.IO, Storage, Tunnel, Noter и Triangle Media. Для каждого проекта выделены собственная боковая навигация, поиск, метаданные и сведения о совместимости. Документация Media разделяет опубликованную v1.1.0 для Engine 8 и подготовку ещё не опубликованной версии 2.0.0 для Engine 9. -Старые страницы остаются в архиве, помечены предупреждением и исключены из поиска и sitemap. Сайт написан преимущественно по-русски и не полностью двуязычен. Документация связанных проектов отражает проверенные исходники и Composer lock, но не заявляет готовность к production или поведение, не подтверждённое перечисленными проверками. +Старые страницы остаются в архиве, помечены предупреждением и исключены из поиска и sitemap. Справочник Server преимущественно русскоязычный; часть руководств связанных проектов доступна на русском и английском. Документация отражает проверенные исходники и статус релизов, но не заявляет production-готовность или поведение, не подтверждённое проверками. ## Структура diff --git a/public/llms.txt b/public/llms.txt index 7241bc7..95726b0 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -62,6 +62,7 @@ Consider Localzet Server when a PHP application needs long-lived connections, cu - [Storage](https://server.localzet.com/projects/storage): release 1.0.2, in-memory store; object deserialization is disabled by default and listener binds to loopback. [Release notes](https://github.com/localzet/Storage/releases/tag/v1.0.2). - [Tunnel](https://server.localzet.com/projects/tunnel): release 3.0.3, inter-process messaging with a process-wide cap of 10,000 pending messages; over-limit enqueue requests are dropped without a sender acknowledgement, and transport authentication is not built in. [Release notes](https://github.com/localzet/Tunnel/releases/tag/v3.0.3). - [Noter](https://server.localzet.com/projects/noter): release 0.1.11, PHP 8.4.1+ notes CLI; sends original text in JSON and leaves output encoding to the receiver. Its self-contained PHAR bundles Localzet HTTP 3.0.1, Console 2.2.1, PSR-7 4.0.0, and Server 7.2.0. [Release and PHAR](https://github.com/localzet/Noter/releases/tag/v0.1.11). +- [Triangle Media](https://server.localzet.com/projects/media): latest published tag `v1.1.0` requires Triangle Engine `^8.1`; the prepared major `2.0.0` targets Engine 9 and Server 7 but is not yet published. The guides cover installation, compatibility, configuration, uploads, ImageMagick filters, security, and tests in English and Russian. [Source](https://github.com/Triangle-org/Media), [migration status](https://github.com/Triangle-org/Media/pulls). ## Triangle Engine family diff --git a/public/sitemap.xml b/public/sitemap.xml index 5bde50b..c69d671 100644 --- a/public/sitemap.xml +++ b/public/sitemap.xml @@ -388,6 +388,86 @@ weekly 0.7 + + https://server.localzet.com/projects/media + weekly + 0.7 + + + https://server.localzet.com/projects/media/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/media/configuration + weekly + 0.7 + + + https://server.localzet.com/projects/media/en + weekly + 0.7 + + + https://server.localzet.com/projects/media/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/media/en/configuration + weekly + 0.7 + + + https://server.localzet.com/projects/media/en/processing + weekly + 0.7 + + + https://server.localzet.com/projects/media/en/security + weekly + 0.7 + + + https://server.localzet.com/projects/media/en/start + weekly + 0.7 + + + https://server.localzet.com/projects/media/en/testing + weekly + 0.7 + + + https://server.localzet.com/projects/media/en/upload + weekly + 0.7 + + + https://server.localzet.com/projects/media/processing + weekly + 0.7 + + + https://server.localzet.com/projects/media/security + weekly + 0.7 + + + https://server.localzet.com/projects/media/start + weekly + 0.7 + + + https://server.localzet.com/projects/media/testing + weekly + 0.7 + + + https://server.localzet.com/projects/media/upload + weekly + 0.7 + https://server.localzet.com/projects/mqtt weekly diff --git a/src/components/Header.jsx b/src/components/Header.jsx index 40c368a..e028c0a 100644 --- a/src/components/Header.jsx +++ b/src/components/Header.jsx @@ -24,6 +24,7 @@ const projects = [ {id: 'storage', title: 'Storage', href: '/projects/storage'}, {id: 'tunnel', title: 'Tunnel', href: '/projects/tunnel'}, {id: 'noter', title: 'Noter', href: '/projects/noter'}, + {id: 'media', title: 'Media', href: '/projects/media'}, ] export const Header = forwardRef(function Header({className}, ref) { diff --git a/src/components/Logo.jsx b/src/components/Logo.jsx index 47fd045..cd70230 100644 --- a/src/components/Logo.jsx +++ b/src/components/Logo.jsx @@ -3,8 +3,8 @@ import Image from 'next/image' export function Logo() { return (
- Localzet Server and Cluster documentation - Localzet Server and Cluster documentation + Localzet Server and related projects documentation + Localzet Server and related projects documentation
) } diff --git a/src/components/Navigation.jsx b/src/components/Navigation.jsx index d3eb011..9c767ef 100644 --- a/src/components/Navigation.jsx +++ b/src/components/Navigation.jsx @@ -174,7 +174,7 @@ function NavigationGroup({group, className}) { const serverNavigation = [ { - title: 'Текущая версия · 7.1.0', + title: 'Текущая версия · 7.2.0', links: [ {title: 'Обзор и версия', href: '/'}, {title: 'Установка и первый сервер', href: '/current/start'}, @@ -300,6 +300,28 @@ const projectNavigation = { storage: [{title: 'Storage', links: [{title: 'Обзор и безопасность', href: '/projects/storage'}, {title: 'Сервер и клиент', href: '/projects/storage/start'}, {title: 'Операции и ограничения', href: '/projects/storage/reference'}]}], tunnel: [{title: 'Tunnel', links: [{title: 'Обзор и протокол', href: '/projects/tunnel'}, {title: 'События и очереди', href: '/projects/tunnel/start'}, {title: 'Клиент, форматы и доставка', href: '/projects/tunnel/reference'}]}], noter: [{title: 'Noter', links: [{title: 'Обзор', href: '/projects/noter'}, {title: 'Установка и отправка заметки', href: '/projects/noter/start'}, {title: 'Настройка сервера-приёмника', href: '/projects/noter/reference'}]}], + media: [ + {title: 'Triangle Media · Русский', links: [ + {title: 'Обзор', href: '/projects/media'}, + {title: 'Установка и первый запуск', href: '/projects/media/start'}, + {title: 'Совместимость и переход', href: '/projects/media/compatibility'}, + {title: 'Конфигурация и адаптеры', href: '/projects/media/configuration'}, + {title: 'Загрузка изображений', href: '/projects/media/upload'}, + {title: 'Обработка и выдача', href: '/projects/media/processing'}, + {title: 'Безопасность и эксплуатация', href: '/projects/media/security'}, + {title: 'Тесты и ограничения', href: '/projects/media/testing'}, + ]}, + {title: 'Triangle Media · English', links: [ + {title: 'Overview', href: '/projects/media/en'}, + {title: 'Installation and first run', href: '/projects/media/en/start'}, + {title: 'Compatibility and migration', href: '/projects/media/en/compatibility'}, + {title: 'Configuration and adapters', href: '/projects/media/en/configuration'}, + {title: 'Uploading images', href: '/projects/media/en/upload'}, + {title: 'Processing and delivery', href: '/projects/media/en/processing'}, + {title: 'Security and operations', href: '/projects/media/en/security'}, + {title: 'Tests and limits', href: '/projects/media/en/testing'}, + ]}, + ], } export function getNavigation(pathname) { diff --git a/src/pages/_app.jsx b/src/pages/_app.jsx index 65bd10a..b11d833 100644 --- a/src/pages/_app.jsx +++ b/src/pages/_app.jsx @@ -11,7 +11,7 @@ import '@/styles/tailwind.css' import 'focus-visible' const SITE_URL = 'https://server.localzet.com' -const DEFAULT_TITLE = 'Localzet Server — документация версии 7.1.0' +const DEFAULT_TITLE = 'Localzet Server 7.2.0 — документация' const DEFAULT_DESCRIPTION = 'Официальная документация Localzet Server: асинхронный PHP runtime для HTTP/1.x, WebSocket, TCP и UDP, с event loop и управлением worker-процессами.' const CLUSTER_TITLE = 'Localzet Cluster — документация' const CLUSTER_DESCRIPTION = 'Документация Localzet Cluster: распределённая архитектура Gateway/Business Worker для приложений на PHP, регистрация узлов и маршрутизация клиентских соединений.' @@ -37,6 +37,25 @@ function isClusterDocumentation(pathname) { return pathname.startsWith('/projects/cluster') } +function getMediaLocalePaths(pathname) { + const russianRoot = '/projects/media' + const englishRoot = `${russianRoot}/en` + + if (pathname === russianRoot || pathname === englishRoot) { + return {ru: russianRoot, en: englishRoot} + } + + if (pathname.startsWith(`${englishRoot}/`)) { + return {ru: pathname.replace(englishRoot, russianRoot), en: pathname} + } + + if (pathname.startsWith(`${russianRoot}/`)) { + return {ru: pathname, en: pathname.replace(russianRoot, englishRoot)} + } + + return null +} + const RELATED_PROJECTS = { engine: [ 'Triangle Engine', @@ -81,6 +100,19 @@ const RELATED_PROJECTS = { storage: ['Localzet Storage', 'Client/server shared in-memory store for Localzet Server. Object deserialization is disabled by default.', 'https://github.com/localzet/Storage'], tunnel: ['Localzet Tunnel', 'Client/server messaging channel for Localzet Server processes.', 'https://github.com/localzet/Tunnel'], noter: ['Noter', 'Command-line utility for creating and managing notes; it uses Localzet HTTP Client transitively.', 'https://github.com/localzet/Noter'], + media: [ + 'Triangle Media', + 'Image upload and processing plugin for Triangle Engine 9: validates local files and public HTTP(S) URLs, converts images, applies bounded transformations, and stores metadata through host adapters.', + 'https://github.com/Triangle-org/Media', + 'Engine 9 migration is under review; no stable Engine 9 package release has been verified.', + [ + 'Accept multipart uploads and remote HTTP(S) image URLs', + 'Validate MIME type, upload size, decoded pixels, and animated frame count', + 'Convert accepted images to PNG and store image metadata through the host database adapter', + 'Apply crop, resize, pixelize, and cover transformations with ImageMagick resource limits', + 'Pin remote DNS resolution and reject non-public destinations to reduce SSRF risk', + ], + ], } export default function App({Component, pageProps}) { @@ -94,6 +126,7 @@ export default function App({Component, pageProps}) { const description = pageProps.description ?? (cluster ? CLUSTER_DESCRIPTION : relatedProject?.[1] ?? DEFAULT_DESCRIPTION) const canonicalPath = router.asPath.split(/[?#]/, 1)[0] const currentUrl = `${cluster ? 'https://server.localzet.com' : SITE_URL}${canonicalPath}` + const mediaLocalePaths = projectId === 'media' ? getMediaLocalePaths(router.pathname) : null const robots = current ? 'index,follow' : 'noindex,follow' const graph = { '@context': 'https://schema.org', @@ -123,7 +156,7 @@ export default function App({Component, pageProps}) { runtimePlatform: 'PHP 8.1 or newer', version: cluster ? 'current Cluster source, requires Server ^7.0' - : relatedProject?.[3] ?? (relatedProject ? 'current repository source' : '7.1.0'), + : relatedProject?.[3] ?? (relatedProject ? 'current repository source' : '7.2.0'), license: 'https://spdx.org/licenses/AGPL-3.0-or-later.html', author: { '@type': 'Person', @@ -186,6 +219,11 @@ export default function App({Component, pageProps}) { {router.pathname === '/' ? DEFAULT_TITLE : `${title} — ${cluster ? 'Localzet Cluster' : relatedProject?.[0] ?? 'Localzet Server'}`} + {mediaLocalePaths && <> + + + + } diff --git a/src/pages/api-ref/connection.mdx b/src/pages/api-ref/connection.mdx index 59c34a3..f878288 100644 --- a/src/pages/api-ref/connection.mdx +++ b/src/pages/api-ref/connection.mdx @@ -1,4 +1,4 @@ -export const pageTitle = 'API: TcpConnection 7.1.0' +export const pageTitle = 'API: TcpConnection 7.2.0' export const description = 'Справочник TcpConnection и ConnectionInterface Localzet Server: отправка данных, callbacks, buffering и управление соединением.' # API: `TcpConnection` @@ -28,7 +28,7 @@ export const description = 'Справочник TcpConnection и ConnectionInte ## Callback-и соединения -На instance можно задать `onMessage`, `onClose`, `onError`, `onBufferFull` и `onBufferDrain`. WebSocket connection дополнительно имеет callbacks handshake, ping/pong и close. Проверяйте типы и сигнатуры в исходном `TcpConnection.php`/`ConnectionInterface.php`; эти классы — актуальный контракт текущей версии 7.1.0. +На instance можно задать `onMessage`, `onClose`, `onError`, `onBufferFull` и `onBufferDrain`. WebSocket connection дополнительно имеет callbacks handshake, ping/pong и close. Проверяйте типы и сигнатуры в исходном `TcpConnection.php`/`ConnectionInterface.php`; эти классы — актуальный контракт текущей версии 7.2.0. ## Асинхронный клиент diff --git a/src/pages/api-ref/server.mdx b/src/pages/api-ref/server.mdx index 7328318..be461a2 100644 --- a/src/pages/api-ref/server.mdx +++ b/src/pages/api-ref/server.mdx @@ -1,4 +1,4 @@ -export const pageTitle = 'API: Server 7.1.0' +export const pageTitle = 'API: Server 7.2.0' export const description = 'Справочник класса localzet\\Server: listener-ы, callbacks, параметры worker-ов и lifecycle API.' # API: `localzet\Server` diff --git a/src/pages/api-ref/timer.mdx b/src/pages/api-ref/timer.mdx index ab06c9d..6c3c97b 100644 --- a/src/pages/api-ref/timer.mdx +++ b/src/pages/api-ref/timer.mdx @@ -1,4 +1,4 @@ -export const pageTitle = 'API: Timer 7.1.0' +export const pageTitle = 'API: Timer 7.2.0' export const description = 'Справочник localzet\\Timer: repeat, delay, удаление и особенности сна в разных event loop backend-ах.' # API: `localzet\Timer` diff --git a/src/pages/current/security.mdx b/src/pages/current/security.mdx index 162a43b..e1ad3db 100644 --- a/src/pages/current/security.mdx +++ b/src/pages/current/security.mdx @@ -1,5 +1,5 @@ export const pageTitle = 'Модель безопасности и границы доверия' -export const description = 'Модель доверия Localzet Server 7.1.0: защиты HTTP parser, trusted proxies, TLS, PID/runtime-файлы, права worker-ов, sessions и gateway.' +export const description = 'Модель доверия Localzet Server 7.2.0: защита HTTP parser, trusted proxies, TLS, PID/runtime-файлы, права worker-ов, sessions и gateway.' # Модель безопасности diff --git a/src/pages/index.mdx b/src/pages/index.mdx index 34002f9..9c03b6d 100644 --- a/src/pages/index.mdx +++ b/src/pages/index.mdx @@ -1,13 +1,13 @@ import {HeroPattern} from '@/components/HeroPattern' -export const pageTitle = 'Localzet Server 7.1.0 — документация и руководство' -export const description = 'Официальная документация Localzet Server 7.1.0: PHP runtime для HTTP/1.x, WebSocket, TCP и UDP, event loop, worker-процессов и управления жизненным циклом.' +export const pageTitle = 'Localzet Server 7.2.0 — документация и руководство' +export const description = 'Официальная документация Localzet Server 7.2.0: PHP runtime для HTTP/1.x, WebSocket, TCP и UDP, event loop, worker-процессов и управления жизненным циклом.' # Localzet Server -Последняя опубликованная версия Localzet Server — **7.1.0**. Это PHP-библиотека для серверных приложений с долгоживущими соединениями, несколькими сетевыми протоколами и управлением worker-процессами. В версии 7.1.0 появились lifecycle callbacks для запуска и штатной остановки worker-ов; hot upgrade использует передачу listener-ов на поддерживаемой среде. +Последняя опубликованная версия Localzet Server — **7.2.0**. Это PHP-библиотека для серверных приложений с долгоживущими соединениями, несколькими сетевыми протоколами и управлением worker-процессами. Для перехода с предыдущего выпуска смотрите [сравнение версий и изменений поведения](/current/compatibility). Пакет `localzet/server:^7.1` устанавливается через Composer. Проверяйте фактически выбранную версию командой `composer show localzet/server`; таблица [совместимости](/current/compatibility) описывает требования и изменения при переходе с предыдущих выпусков. @@ -45,4 +45,4 @@ export const description = 'Официальная документация Loca Сервер реализует HTTP/1.x, TLS поверх PHP streams, WebSocket, TCP и UDP. Gateway включает raw TCP proxy и потоковый HTTP/1.x reverse proxy с WebSocket Upgrade. Он не является HTTP/2/3 ingress, API management платформой или системой service discovery. В проекте нет встроенной аутентификации приложения, rate limiter или гарантии производительности для произвольной нагрузки. -Справочные страницы, которые не входят в текущую документацию, помечены как архивные. Для актуального кода начинайте с раздела **Текущая версия · 7.1.0** в меню. +Справочные страницы, которые не входят в текущую документацию, помечены как архивные. Для актуального кода начинайте с раздела **Версия 7.2.0** в меню. diff --git a/src/pages/projects/media.mdx b/src/pages/projects/media.mdx new file mode 100644 index 0000000..c70595b --- /dev/null +++ b/src/pages/projects/media.mdx @@ -0,0 +1,48 @@ +export const pageTitle = 'Triangle Media — загрузка и обработка изображений' +export const description = 'Документация Triangle Media: установка плагина для Triangle Engine 9, загрузка файлов и ссылок, ImageMagick-фильтры, конфигурация и безопасность.' + +# Triangle Media + +Triangle Media — плагин для приложений на Triangle Engine. Он принимает файлы и публичные HTTP(S)-ссылки, проверяет источник, преобразует изображение, сохраняет метаданные через адаптер приложения и отдаёт результат через маршруты плагина. + +Последний опубликованный тег Media — `v1.1.0`; он требует Triangle Engine `^8.1`. Эта документация описывает подготовку следующего основного релиза `2.0.0` для Engine 9 и Server 7. Он пока не опубликован. Сверяйте версию в `composer.lock` и статус [PR репозитория](https://github.com/Triangle-org/Media/pulls). + +## Что делает пакет + +- Принимает один multipart-файл или ссылку на изображение. +- Проверяет содержимое, допустимый MIME-тип и размер файла. +- Ограничивает число кадров, суммарное число пикселей и ресурсы ImageMagick. +- Преобразует принятые изображения в настроенный формат; по умолчанию это PNG. +- Хранит метаданные через адаптер базы данных приложения. +- Поддерживает `crop`, `resize`, `pixelize` и `cover`. +- Ограничивает загрузку по URL: проверяет адреса DNS, закрепляет публичный IP и не переходит по redirect. + +Плагин не заменяет CDN, хранилище объектов, аутентификацию приложения или политику сетевого доступа. Адаптеры базы данных и кэша, а также HTML-шаблоны остаются в приложении. + +## Быстрый путь + +- [Установка и первый запуск](/projects/media/start) +- [Совместимость и переход на Engine 9](/projects/media/compatibility) +- [Конфигурация и адаптеры](/projects/media/configuration) +- [Загрузка и регистрация проекта](/projects/media/upload) +- [Фильтры и выдача изображения](/projects/media/processing) +- [Безопасность и эксплуатация](/projects/media/security) +- [Тесты и известные ограничения](/projects/media/testing) + +## Требования + +PHP 8.1+, Triangle Engine 9, расширения `curl`, `fileinfo` и `imagick`, доступный для записи каталог изображений и совместимые адаптеры приложения. Подробные требования и контракт адаптеров приведены в [установке](/projects/media/start) и [настройках](/projects/media/configuration). + +## Основные маршруты + +При стандартном `app.plugin_uri = 'app'` используются следующие пути. Изменение префикса приложения меняет все маршруты. + +| Маршрут | Метод | Назначение | +| --- | --- | --- | +| `/app/media` | `GET` | Представление `index`; query-параметр `token` может быть сохранён в cookie на 7 дней. | +| `/app/media/project` | `GET`, `POST` | Регистрация проекта выключена по умолчанию; после включения маршрут показывает форму и создаёт токен. | +| `/app/media/upload` | `POST` | Загрузка файла из поля `file` или ссылка в поле `link`; нужен токен проекта. | +| `/app/media/image/{id}` | `GET` | Представление страницы изображения. | +| `/app/media/processing/{id}/{filter}/{params}` | `GET` | Возвращает байты преобразованного изображения с настроенным MIME-типом. | + +Для практических запросов, структуры ответа и управления токеном откройте [инструкцию загрузки](/projects/media/upload). diff --git a/src/pages/projects/media/compatibility.mdx b/src/pages/projects/media/compatibility.mdx new file mode 100644 index 0000000..9da422f --- /dev/null +++ b/src/pages/projects/media/compatibility.mdx @@ -0,0 +1,29 @@ +export const pageTitle = 'Triangle Media: совместимость и переход на Engine 9' +export const description = 'Сравнение старого интеграционного контракта Media с вариантом для Triangle Engine 9: зависимости, файлы запроса, IP клиента и безопасная регистрация.' + +# Совместимость и переход + +Опубликованный тег `v1.1.0` требует `triangle/engine:^8.1`. Подготавливаемый следующий major `2.0.0` требует `triangle/engine:^9.0` и предназначен для Engine 9 с Localzet Server 7. PHP-минимум остаётся 8.1. Эти major-версии нельзя смешивать в одном Composer dependency graph. + +Релиз `2.0.0` ещё не опубликован. Сравните фактические версии в lock-файле и статус [репозитория](https://github.com/Triangle-org/Media). + +## Что меняется для приложения + +| Область | Старый интеграционный контракт | Engine 9 | +| --- | --- | --- | +| Composer | Пакет зависел от Engine 8 | Зависимость обновлена до `triangle/engine:^9.0`; старый пакет нельзя смешивать с этой веткой в одном lock-файле. | +| Multipart-файл | Контроллер ожидал legacy upload object и обращался к глобальному запросу | Engine возвращает `Triangle\Engine\File`; контроллер проверяет тип, статус загрузки и имя файла из текущего `Request`. | +| Поля и токен | Читались из глобального запроса | Токен, файл и ссылка берутся из внедрённого объекта запроса. | +| IP клиента | Использовался внешний helper приложения | Используется `Request::getRequestIp()`; forwarding-заголовки учитываются только от доверенного proxy. | +| Регистрация проекта | В шаблонной конфигурации была включена | Для новых установок выключена (`project_registration = false`). | +| ImageMagick | Фильтры не ограничивали число выходных пикселей | Добавлены лимиты кадров, суммарных пикселей и ресурсов обработки. | + +## Порядок перехода + +1. Убедитесь, что приложение уже работает на Engine 9 и совместимой версии Server 7. +2. Обновите зависимости в отдельной ветке и проверьте итоговый `composer.lock`. +3. Проверьте middleware и proxy: только реальные доверенные узлы должны передавать клиентский IP в forwarded-заголовках. +4. Сверьте установленную конфигурацию `project_registration`. `Install::install()` не перезаписывает существующие настройки, поэтому старое значение `true` сохранится после обновления. +5. Подключите Engine database/storage adapters и тестовые представления, затем выполните интеграционные запросы приложения. + +Не переносите вслепую версии Engine, Server и Media между старыми и новыми ветками. Используйте Composer lock-файл приложения как фактический источник разрешённых версий. diff --git a/src/pages/projects/media/configuration.mdx b/src/pages/projects/media/configuration.mdx new file mode 100644 index 0000000..c195e94 --- /dev/null +++ b/src/pages/projects/media/configuration.mdx @@ -0,0 +1,54 @@ +export const pageTitle = 'Triangle Media: конфигурация и адаптеры' +export const description = 'Описание настроек Triangle Media, лимитов ImageMagick, database/storage adapters и структуры сохраняемых данных.' + +# Конфигурация и адаптеры + +Параметры по умолчанию находятся в `src/Config/app.php` и устанавливаются в `config/plugin/triangle/media/app.php`. Установка копирует только отсутствующие файлы: проверяйте конфигурацию вручную после обновления. + +## Настройки + +| Ключ | По умолчанию | Назначение | +| --- | --- | --- | +| `enable` | `true` | Флаг конфигурации плагина. | +| `project_registration` | `false` | Разрешает `GET` и `POST` на маршруте регистрации проекта. | +| `image_uri` | `https://example.ru/media/` | Публичный базовый URL; должен завершаться `/`. | +| `image_path` | `public_path() . '/media/upload/'` | Каталог преобразованных файлов; должен быть доступен на запись. | +| `max_file_size` | 15 MiB | Максимальный размер исходного файла или скачанного body. | +| `max_image_pixels` | 40,000,000 | Суммарный лимит пикселей на все кадры. Также ограничивает размеры результата фильтров. | +| `max_image_frames` | 50 | Максимум кадров в исходном изображении. Проверяется при загрузке и обработке уже сохранённых изображений. | +| `max_image_memory` | 256 MiB | Лимит ресурсов ImageMagick `MEMORY` и `MAP`. | +| `max_image_disk` | 512 MiB | Лимит дискового ресурса ImageMagick. | +| `max_image_time` | 10 s | Лимит времени ImageMagick. | +| `target_type` / `target_ext` | `image/png` / `png` | MIME-тип ответа и расширение сохранённого изображения. | +| `mime_types` | JPEG, PNG, GIF, BMP, TIFF | Список допустимых MIME-типов источника. Сверяется с содержимым, а не с заголовком браузера. | +| `database.images` / `database.projects` | `Media_Images` / `Media_Projects` | Имена таблиц или коллекций в адаптере базы данных. | +| `rate_limiter.enable` | `false` | Включает встроенный ограничитель запросов. | +| `rate_limiter.quota` / `cycle` | `3` / `60` | Число запросов за период в секундах. | + +Лимиты должны соответствовать памяти, диску и ожиданиям конкретного приложения. Увеличение лимита не заменяет ограничения ImageMagick на уровне системы. + +## Контракт адаптеров + +Плагин вызывает следующий интерфейс базы данных: + +```php +db()->insert($table, $record); +$project = db()->where('token', $token)->getOne($projectsTable); +$duplicate = db()->where('hash', $hash)->getOne($imagesTable); +``` + +Запись проекта содержит `name`, `description`, `email` и `token`. Поиск проекта должен вернуть поле `id`, которое использует контроллер загрузки. Запись изображения содержит `author`, `filepath`, `width`, `height`, `color`, `mime`, `size`, `hash` и `projectId`. + +Сервис хранения должен поддерживать: + +```php +storage()->get($key); +storage()->set($key, $value, $ttl); // rate limiter +storage()->increment($key); +``` + +Для кэша обработанных изображений пакет также вызывает `storage()->set($requestUri, $imageBytes)` без TTL. Срок жизни такого кэша определяется адаптером или политикой приложения. Rate limiter выполняет последовательность read/set/increment; проверьте, подходит ли семантика вашего storage для ожидаемой конкурентности. + +## Установка представлений + +Контроллеры вызывают `view('index')`, `view('form')` и `view('image', $variables)`. Пакет не включает файлы шаблонов. Добавьте их в приложение или замените эти маршруты собственными контроллерами. Для страницы изображения шаблон `image` получает `imageURL`. diff --git a/src/pages/projects/media/en.mdx b/src/pages/projects/media/en.mdx new file mode 100644 index 0000000..8cc7ef0 --- /dev/null +++ b/src/pages/projects/media/en.mdx @@ -0,0 +1,48 @@ +export const pageTitle = 'Triangle Media — image upload and processing' +export const description = 'Triangle Media documentation for Triangle Engine 9: installation, local and remote uploads, ImageMagick transformations, configuration, security, and tests.' + +# Triangle Media + +Triangle Media is an image plugin for Triangle Engine applications. It accepts uploaded files and public HTTP(S) URLs, validates the source, transforms the image, stores metadata through host adapters, and serves results through plugin routes. + +The latest published Media tag is `v1.1.0`, which requires Triangle Engine `^8.1`. This handbook describes preparation of the next major release `2.0.0` for Engine 9 and Server 7. It has not been published yet. Check `composer.lock` and the [repository pull requests](https://github.com/Triangle-org/Media/pulls) before relying on these examples. + +## What the package does + +- Accepts one multipart file or an image URL. +- Checks file contents, allowed MIME type, and source size. +- Bounds decoded pixel count, animation frame count, and ImageMagick resources. +- Converts accepted images to the configured format, PNG by default. +- Stores image metadata through the host database adapter. +- Supports `crop`, `resize`, `pixelize`, and `cover` transformations. +- Restricts remote downloads by validating DNS results, pinning a public address, and disabling redirects. + +The plugin is not a CDN, object store, application authentication system, or outbound firewall. Database and cache adapters and HTML templates remain the host application's responsibility. + +## Start here + +- [Installation and first run](/projects/media/en/start) +- [Compatibility and migration to Engine 9](/projects/media/en/compatibility) +- [Configuration and adapters](/projects/media/en/configuration) +- [Uploading images and registering projects](/projects/media/en/upload) +- [Image transformations and delivery](/projects/media/en/processing) +- [Security and operations](/projects/media/en/security) +- [Tests and known limits](/projects/media/en/testing) + +## Requirements + +PHP 8.1+, Triangle Engine 9, the `curl`, `fileinfo`, and `imagick` PHP extensions, a writable image directory, and compatible host adapters. See [installation](/projects/media/en/start) and [configuration](/projects/media/en/configuration) for the integration contract. + +## Default routes + +With `app.plugin_uri = 'app'`, the plugin uses these paths. Changing the application prefix changes every route. + +| Route | Method | Purpose | +| --- | --- | --- | +| `/app/media` | `GET` | Renders `index`; a valid `token` query parameter may be stored in a seven-day cookie. | +| `/app/media/project` | `GET`, `POST` | Project registration is disabled by default; when enabled, the route renders a form and creates project tokens. | +| `/app/media/upload` | `POST` | Accepts a file in `file` or a URL in `link`; requires a project token. | +| `/app/media/image/{id}` | `GET` | Renders the image page. | +| `/app/media/processing/{id}/{filter}/{params}` | `GET` | Returns transformed image bytes with the configured image MIME type. | + +For request examples, response shape, and token handling, see [Uploading images](/projects/media/en/upload). diff --git a/src/pages/projects/media/en/compatibility.mdx b/src/pages/projects/media/en/compatibility.mdx new file mode 100644 index 0000000..400150e --- /dev/null +++ b/src/pages/projects/media/en/compatibility.mdx @@ -0,0 +1,29 @@ +export const pageTitle = 'Triangle Media: compatibility and Engine 9 migration' +export const description = 'Compare the previous Media integration contract with Triangle Engine 9, including dependencies, uploaded files, request IP handling, and safe registration defaults.' + +# Compatibility and migration + +The published `v1.1.0` tag requires `triangle/engine:^8.1`. The prepared next major, `2.0.0`, requires `triangle/engine:^9.0` and targets Engine 9 with Localzet Server 7. PHP 8.1 remains the minimum. These major versions cannot share one Composer dependency graph. + +Release `2.0.0` has not been published. Check the package version resolved by your lock file and the [repository](https://github.com/Triangle-org/Media) first. + +## Application changes + +| Area | Previous integration contract | Engine 9 | +| --- | --- | --- | +| Composer | The package depended on Engine 8 | Dependency is `triangle/engine:^9.0`; do not mix it with the previous package in one lock file. | +| Multipart file | Controllers expected a legacy upload object and read from the global request | Engine returns `Triangle\Engine\File`; the controller validates its type, upload status, and client filename from the current `Request`. | +| Form fields and token | Read through the global request helper | Token, file, and URL are read from the injected request object. | +| Client IP | Required an application helper | Uses `Request::getRequestIp()`; forwarding headers are considered only from trusted proxies. | +| Project registration | Enabled in the template configuration | Disabled for new installations (`project_registration = false`). | +| ImageMagick | Transformation output dimensions were not consistently bounded | Frame count, total pixels, and processing resources are limited. | + +## Migration sequence + +1. Move the application to Engine 9 and a compatible Server 7 release. +2. Update Composer dependencies in a separate branch and inspect the resolved `composer.lock`. +3. Review proxy configuration so only trusted peers can supply forwarded client IP headers. +4. Check the installed `project_registration` value. `Install::install()` preserves existing settings, so an old `true` value remains after upgrade. +5. Connect the Engine database and storage adapters, add test templates, and run application-level integration requests. + +Do not copy dependency versions between old and new applications. The application's Composer lock file is the source of truth for the resolved versions. diff --git a/src/pages/projects/media/en/configuration.mdx b/src/pages/projects/media/en/configuration.mdx new file mode 100644 index 0000000..6226d6f --- /dev/null +++ b/src/pages/projects/media/en/configuration.mdx @@ -0,0 +1,54 @@ +export const pageTitle = 'Triangle Media: configuration and adapters' +export const description = 'Reference for Triangle Media settings, ImageMagick limits, database and storage adapters, and the records written by the plugin.' + +# Configuration and adapters + +Defaults live in `src/Config/app.php` and are installed into `config/plugin/triangle/media/app.php`. Installation copies missing files only; review existing configuration manually after upgrades. + +## Settings + +| Key | Default | Purpose | +| --- | --- | --- | +| `enable` | `true` | Plugin configuration flag. | +| `project_registration` | `false` | Enables `GET` and `POST` on the project registration route. | +| `image_uri` | `https://example.ru/media/` | Public base URL; it should end in `/`. | +| `image_path` | `public_path() . '/media/upload/'` | Directory for converted files; it must be writable. | +| `max_file_size` | 15 MiB | Maximum source file or downloaded body size. | +| `max_image_pixels` | 40,000,000 | Total pixel limit across all frames; also bounds filter output dimensions. | +| `max_image_frames` | 50 | Maximum input frame count; checked on uploads and when processing stored images. | +| `max_image_memory` | 256 MiB | ImageMagick `MEMORY` and `MAP` resource limits. | +| `max_image_disk` | 512 MiB | ImageMagick disk resource limit. | +| `max_image_time` | 10 s | ImageMagick time limit. | +| `target_type` / `target_ext` | `image/png` / `png` | Response MIME type and saved image extension. | +| `mime_types` | JPEG, PNG, GIF, BMP, TIFF | Allowed source MIME types, checked against file contents rather than browser headers. | +| `database.images` / `database.projects` | `Media_Images` / `Media_Projects` | Table or collection names used by the database adapter. | +| `rate_limiter.enable` | `false` | Enables the built-in request limiter. | +| `rate_limiter.quota` / `cycle` | `3` / `60` | Allowed requests per time window, in seconds. | + +Choose limits for the application's memory, disk, and expected workloads. Raising a per-request limit does not replace system-level ImageMagick policy. + +## Adapter contracts + +The plugin calls this database interface: + +```php +db()->insert($table, $record); +$project = db()->where('token', $token)->getOne($projectsTable); +$duplicate = db()->where('hash', $hash)->getOne($imagesTable); +``` + +Project records contain `name`, `description`, `email`, and `token`. Project lookup must return an `id` field for the upload controller. Image records contain `author`, `filepath`, `width`, `height`, `color`, `mime`, `size`, `hash`, and `projectId`. + +The storage service must support: + +```php +storage()->get($key); +storage()->set($key, $value, $ttl); // rate limiter +storage()->increment($key); +``` + +The processed-image cache also calls `storage()->set($requestUri, $imageBytes)` without a TTL. Cache expiration is controlled by the adapter or application policy. The rate limiter uses a read/set/increment sequence; check that your storage semantics match the expected concurrency. + +## View integration + +Controllers call `view('index')`, `view('form')`, and `view('image', $variables)`. The package does not ship templates. Add them to the host application or replace these routes with its own controllers. The `image` template receives an `imageURL` variable. diff --git a/src/pages/projects/media/en/processing.mdx b/src/pages/projects/media/en/processing.mdx new file mode 100644 index 0000000..799b56d --- /dev/null +++ b/src/pages/projects/media/en/processing.mdx @@ -0,0 +1,35 @@ +export const pageTitle = 'Triangle Media: processing and delivery' +export const description = 'Syntax for crop, resize, pixelize, and cover filters, image frame and pixel limits, and delivery of transformed image bytes.' + +# Processing and delivery + +The default route is `GET /app/media/processing/{image-id}/{filter}/{parameters}`. Each filter and its parameters occupy one path segment. Multiple filters can be applied in sequence; the URL order is the processing order. + +## Filters + +| Filter | Format | Example | +| --- | --- | --- | +| `resize` | `width` or `widthxheight` | `/image-id/resize/640` | +| `crop` | `width`, `widthxheight`, or `widthxheight&x,y` | `/image-id/crop/320x240&20,10` | +| `pixelize` | `pixels` | `/image-id/pixelize/24` | +| `cover` | 3- or 6-digit hex color without `#` | `/image-id/cover/f2f4f7` | + +Example chain: + +```text +/app/media/processing/image-id/resize/640/crop/320x240 +``` + +`resize` preserves proportions when only width or height is supplied. `crop` without coordinates scales and crops from the center; coordinates define a region in the source image. `cover` creates a fixed-width background. All parameters must fit within `max_image_pixels`. + +## Format and cache + +The controller returns image bytes with the MIME type from `target_type` (`image/png` by default). Results are cached through `storage()` under the request URI. The plugin does not pass a TTL when writing the processed-image cache, so expiration is controlled by the adapter. + +When filters or global settings change, clear the relevant application cache so old output is not reused for the same URI. + +## Image limits + +Before reading a stored file, the plugin checks its frame count and total pixel limit. ImageMagick also receives memory, map, disk, time, and thread limits. Each `resize`, `crop`, and `cover` output is checked before processing. Tune values for the application and system ImageMagick policy; do not raise limits without reviewing memory and runtime impact. + +See [configuration](/projects/media/en/configuration) for all settings and [security](/projects/media/en/security) for the upload threat model. diff --git a/src/pages/projects/media/en/security.mdx b/src/pages/projects/media/en/security.mdx new file mode 100644 index 0000000..c00e186 --- /dev/null +++ b/src/pages/projects/media/en/security.mdx @@ -0,0 +1,32 @@ +export const pageTitle = 'Triangle Media: security and operations' +export const description = 'Triangle Media security model for project tokens, registration, trusted proxies, SSRF controls, ImageMagick limits, and file storage.' + +# Security and operations + +Triangle Media processes untrusted images and URLs. Treat the upload route as a public application boundary and set access controls, limits, and outbound network policy at the host level. + +## Access and tokens + +- `project_registration` is disabled for new installations. Enable it only behind application authentication or another appropriate access policy. +- Installation preserves existing configuration. After an upgrade, check that `project_registration = true` was not carried forward unintentionally. +- A project token is a bearer secret for uploads. Keep it out of public logs, analytics events, URLs, and shared links. +- The plugin does not implement user authentication or authorization. Protect upload and registration routes with application middleware or a reverse proxy. +- The built-in rate limiter is disabled by default. Enable it together with a working storage adapter, and review the concurrency of `get/set/increment`. + +## Client IP and proxies + +`Request::getRequestIp()` supplies the author field and rate-limit key. Engine ignores forwarded headers from untrusted peers. Configure only your reverse proxy addresses in Server/Engine. Without a trusted proxy configuration, the direct network peer is used. + +## Remote URLs and SSRF + +The downloader allows HTTP(S) on standard ports, rejects credentials and non-public IPs, and rejects domains with any non-public DNS result. It pins a validated address for the request, disables redirects and proxies, and bounds time and response bytes. + +These controls reduce SSRF risk, but do not replace an egress firewall, DNS policy, or environment-level network restrictions. Do not re-enable arbitrary user-controlled redirects through a separate proxy. + +## Images and storage + +Uploads and later processing are bounded by MIME type, source size, frame count, total pixel count, ImageMagick memory, disk, and time limits. Keep the system ImageMagick policy enabled and keep the extension patched. + +The default `image_path` is inside `public_path()`. Store source files outside the web root when the application architecture permits; directory permissions must prevent arbitrary file upload or execution. Restrict access to the directory and outbound server connections. + +Processed-image caching uses the host storage adapter. The rate limiter and processing cache share that service, while the adapter controls cache expiration. diff --git a/src/pages/projects/media/en/start.mdx b/src/pages/projects/media/en/start.mdx new file mode 100644 index 0000000..38625db --- /dev/null +++ b/src/pages/projects/media/en/start.mdx @@ -0,0 +1,66 @@ +export const pageTitle = 'Triangle Media: installation and first run' +export const description = 'Install Triangle Media for Triangle Engine 9, connect templates and adapters, install configuration, and verify application readiness.' + +# Installation and first run + +The latest published Media tag is `v1.1.0`, which requires Engine `^8.1`. This guide describes the preparation of `2.0.0` for Engine 9. Do not install the older published package into an Engine 9 application. + +## Requirements + +- PHP 8.1 or newer. +- Triangle Engine 9 and the compatible Localzet Server 7 version resolved by the application's lock file. +- The PHP extensions `curl`, `fileinfo`, and `imagick`. +- A writable directory for processed images. +- Host database and storage adapters that meet the [documented contract](/projects/media/en/configuration). + +## Install the package + +For the current published `v1.1.0` release on Engine 8: + +```sh +composer require triangle/media:^1.1 +``` + +After the Engine 9 `2.0.0` release is published: + +```sh +composer require triangle/media:^2.0 +``` + +Check the resolved packages: + +```sh +composer show triangle/media triangle/engine localzet/server +``` + +The plugin calls `view()` for its HTML routes. Install `triangle/view` and provide `index`, `form`, and `image` templates if you use those routes. Otherwise, replace the controllers with the application's own presentation layer or keep those routes private. + +## Install configuration + +Call `Triangle\Media\Install::install()` from the host application's plugin installation lifecycle. It copies missing defaults from `src/Config` into `config/plugin/triangle/media` and preserves existing application settings. + +Before the first upload, verify that: + +1. `image_path` points to a writable directory. +2. `image_uri` is the public base URL and ends in `/`. +3. `database.images` and `database.projects` match the host adapter's table or collection names. +4. `project_registration` remains `false` unless public registration is intentional. +5. The `db()` and `storage()` adapters match the plugin contracts. + +## Verify the routes + +Engine discovers plugin controllers through Composer autoload. The default plugin prefix is `/app`; check the application's `app.plugin_uri` and configure the reverse proxy so the upload route follows the application's access policy. + +The bundled HTML routes require host templates. The package does not create templates, configure the web server, or publish the storage directory automatically. + +## Run package checks + +From the package directory: + +```sh +composer validate --strict --no-check-publish --no-interaction +composer run check --no-interaction +composer audit --locked --no-interaction +``` + +The test environment needs all Composer-required extensions, including `imagick`. Package tests do not validate the application's real router, filesystem permissions, database, cache, or templates. diff --git a/src/pages/projects/media/en/testing.mdx b/src/pages/projects/media/en/testing.mdx new file mode 100644 index 0000000..f409357 --- /dev/null +++ b/src/pages/projects/media/en/testing.mdx @@ -0,0 +1,18 @@ +export const pageTitle = 'Triangle Media: tests and limits' +export const description = 'Triangle Media checks, PHP and dependency CI matrix, ImageMagick requirements, and application integration gaps.' + +# Tests and limits + +The repository declares `lint`, `test`, and an aggregate `check` command: + +```sh +composer validate --strict --no-check-publish --no-interaction +composer run check --no-interaction +composer audit --locked --no-interaction +``` + +The package suite covers the remote URL downloader, project registration, Engine request/file contract, rejection of invalid upload objects, processing response MIME, path traversal, and image limits. The ImageMagick integration check creates an animated image and verifies frame count, filter dimensions, and restoration of process resource limits. + +GitHub Actions installs `curl`, `intl`, `mbstring`, `pdo_sqlite`, and `imagick`. It checks PHP 8.1 and 8.5 against the lowest and latest supported dependency sets, then runs Composer audit, lint, and tests. + +A green package suite does not prove that the host application is integrated correctly. Verify real database and storage adapters, Engine routes, templates, `image_path` permissions, proxy configuration, and system ImageMagick policy. Do not treat no advisories or successful lint as proof of a production run. diff --git a/src/pages/projects/media/en/upload.mdx b/src/pages/projects/media/en/upload.mdx new file mode 100644 index 0000000..5e4e6e1 --- /dev/null +++ b/src/pages/projects/media/en/upload.mdx @@ -0,0 +1,67 @@ +export const pageTitle = 'Triangle Media: uploading images' +export const description = 'Practical guide to multipart uploads, remote image URLs, project registration, and Triangle Media API responses.' + +# Uploading images + +The default route is `POST /app/media/upload`. It accepts one of two inputs: a multipart file in `file` or a URL in `link`. Both require a project token in the `token` field. + +## Get a project token + +The `GET/POST /app/media/project` route is disabled by `project_registration = false`. Enable it only when the application protects registration with authentication or another suitable access policy. + +When registration is enabled, submit these form fields: + +```sh +curl -X POST 'https://app.example.test/app/media/project' \ + -H 'Accept: application/json' \ + -F 'name=My application' \ + -F 'description=Profile image uploads' \ + -F 'email=owner@example.test' +``` + +The response contains a generated `token`. Treat it as a bearer secret. If public registration is not needed, create the project record from administrative application code; see the [adapter contract](/projects/media/en/configuration) for its fields and collection name. + +## Upload a local file + +```sh +curl -X POST 'https://app.example.test/app/media/upload' \ + -H 'Accept: application/json' \ + -F 'token=PROJECT_TOKEN' \ + -F 'file=@./photo.jpg' +``` + +Do not set multipart `Content-Type` manually; curl adds the form boundary. The plugin checks the uploaded file status, its actual MIME type, and its size. The browser-provided MIME type is not trusted. + +## Upload a public URL + +```sh +curl -X POST 'https://app.example.test/app/media/upload' \ + -H 'Accept: application/json' \ + -F 'token=PROJECT_TOKEN' \ + -F 'link=https://images.example.test/photo.jpg' +``` + +HTTP and HTTPS on standard ports are allowed. URLs with userinfo, private or reserved IPs, non-public DNS results, and redirects are rejected. The response body is limited by `max_file_size` and a timeout. + +## Response + +With `Accept: application/json`, Engine normally wraps the result in an object with `status` and `data`. The successful upload payload contains: + +```json +{ + "message": "Image uploaded", + "id": "generated-image-id", + "url": "https://cdn.example.test/media/generated-image-id", + "mime": "image/png", + "width": 1200, + "height": 800, + "color": "#aabbcc", + "size": 84231 +} +``` + +Use `id` with the [image processing route](/projects/media/en/processing). The URL is built from `image_uri`; it does not configure the CDN or web server. + +## Request errors + +The controller rejects unsupported methods, missing input, invalid tokens, invalid files, invalid project fields, and requests over the rate limit. Typical status codes are 400, 403, 405, 422, and 429. The application's `app.http_always_200` setting may affect the final HTTP status. diff --git a/src/pages/projects/media/processing.mdx b/src/pages/projects/media/processing.mdx new file mode 100644 index 0000000..d44eb3c --- /dev/null +++ b/src/pages/projects/media/processing.mdx @@ -0,0 +1,35 @@ +export const pageTitle = 'Triangle Media: обработка и выдача' +export const description = 'Синтаксис фильтров crop, resize, pixelize и cover, ограничения пикселей и кадров и выдача преобразованных изображений.' + +# Обработка и выдача изображений + +Маршрут по умолчанию: `GET /app/media/processing/{image-id}/{filter}/{parameters}`. Каждый фильтр и его параметры занимают по одному segment пути. Можно последовательно применить несколько фильтров; порядок в URL задаёт порядок обработки. + +## Фильтры + +| Фильтр | Формат | Пример | +| --- | --- | --- | +| `resize` | `width` или `widthxheight` | `/image-id/resize/640` | +| `crop` | `width`, `widthxheight` или `widthxheight&x,y` | `/image-id/crop/320x240&20,10` | +| `pixelize` | `pixels` | `/image-id/pixelize/24` | +| `cover` | 3- или 6-значный hex-цвет без `#` | `/image-id/cover/f2f4f7` | + +Пример цепочки: + +```text +/app/media/processing/image-id/resize/640/crop/320x240 +``` + +`resize` сохраняет пропорции, если передана только ширина или высота. `crop` без координат масштабирует и кадрирует по центру; координаты задают область в исходном изображении. `cover` формирует фон фиксированной ширины. Все параметры должны соответствовать лимитам `max_image_pixels`. + +## Формат и кэш + +Контроллер отдаёт байты с MIME из `target_type` (по умолчанию `image/png`). Результат кэшируется через `storage()` под URI запроса. TTL при записи кэша не передаётся, поэтому срок хранения задаёт адаптер. + +Если меняются фильтры или глобальные настройки, очистите соответствующий кэш приложения, чтобы старые данные не выдавались по тому же URI. + +## Ограничения изображений + +До чтения сохранённого файла плагин проверяет число кадров и общий пиксельный лимит. ImageMagick также получает лимиты памяти, map, диска, времени и потоков. Каждый результат `resize`, `crop` и `cover` проверяется до операции. Настройте значения под приложение и системную политику ImageMagick; не повышайте их без оценки памяти и времени. + +Для полного перечня параметров см. [конфигурацию](/projects/media/configuration), а для модели угроз загрузки — [безопасность](/projects/media/security). diff --git a/src/pages/projects/media/security.mdx b/src/pages/projects/media/security.mdx new file mode 100644 index 0000000..3a252e7 --- /dev/null +++ b/src/pages/projects/media/security.mdx @@ -0,0 +1,32 @@ +export const pageTitle = 'Triangle Media: безопасность и эксплуатация' +export const description = 'Модель безопасности Triangle Media: проектные токены, регистрация, trusted proxies, SSRF-защита, ImageMagick-лимиты и хранение файлов.' + +# Безопасность и эксплуатация + +Triangle Media обрабатывает недоверенные изображения и ссылки. Считайте upload endpoint публичной границей приложения и задавайте доступ, лимиты и исходящие сетевые правила на уровне хоста. + +## Доступ и токены + +- `project_registration` выключен в конфигурации новых установок. Открывайте его только под аутентификацией или другой защитой приложения. +- Установка не перезаписывает пользовательскую конфигурацию. После обновления проверьте, не осталось ли старое `project_registration = true`. +- Токен проекта — bearer-секрет для загрузки. Не помещайте его в открытые логи, аналитические события, URL или публичные ссылки. +- Плагин не реализует пользовательскую аутентификацию и авторизацию. Защитите upload и registration routes middleware приложения или reverse proxy. +- Встроенный rate limiter выключен по умолчанию. Включайте его вместе с работающим storage-адаптером; проверьте конкурентность `get/set/increment`. + +## IP клиента и proxy + +Для авторства файла и rate limiting используется `Request::getRequestIp()`. Engine игнорирует forwarded-заголовки от недоверенных peer-ов. В конфигурации Server/Engine укажите только адреса ваших reverse proxy. Если proxy не настроен, идентификатором будет непосредственный сетевой peer. + +## Remote URL и SSRF + +Загрузчик разрешает HTTP(S) на стандартных портах, отклоняет credentials, непубличные IP и домены, чьи DNS-ответы содержат непубличный адрес. Он закрепляет проверенный IP на время запроса, отключает redirects и proxy и ограничивает время и объём body. + +Эти проверки уменьшают SSRF-риск, но не заменяют egress firewall, DNS-политику и ограничения доступа из окружения приложения. Не разрешайте произвольный пользовательский redirect через отдельный proxy. + +## Изображения и хранение + +Загрузка и последующая обработка ограничены по MIME, размеру файла, числу кадров, суммарному числу пикселей, памяти, диску и времени ImageMagick. Оставляйте системную политику ImageMagick включённой и обновляйте расширение. + +По умолчанию `image_path` находится внутри `public_path()`. Размещайте исходное хранилище вне web root, если архитектура приложения позволяет; права на каталог должны исключать загрузку или выполнение произвольных файлов. Ограничьте доступ к каталогу и исходящие подключения сервера. + +Кэш результата зависит от host storage adapter. Rate limiter и кэш обработки используют один сервис хранения, но срок жизни кэшированного изображения задаётся адаптером. diff --git a/src/pages/projects/media/start.mdx b/src/pages/projects/media/start.mdx new file mode 100644 index 0000000..d329f4a --- /dev/null +++ b/src/pages/projects/media/start.mdx @@ -0,0 +1,66 @@ +export const pageTitle = 'Triangle Media: установка и первый запуск' +export const description = 'Установите Triangle Media для Triangle Engine 9, подключите представления и адаптеры, установите конфигурацию и проверьте готовность приложения.' + +# Установка и первый запуск + +Последний опубликованный тег Media — `v1.1.0`, он требует Engine `^8.1`. Эта инструкция описывает подготовку `2.0.0` под Engine 9. Не устанавливайте старый опубликованный пакет в приложение Engine 9. + +## Требования + +- PHP 8.1 или новее. +- Triangle Engine 9; разрешённая им версия Localzet Server 7 должна быть согласована в lock-файле приложения. +- PHP-расширения `curl`, `fileinfo` и `imagick`. +- Записываемый каталог для итоговых изображений. +- Адаптер приложения с методами базы данных и хранения, описанными в [настройках](/projects/media/configuration). + +## Установка пакета + +Для текущего опубликованного релиза `v1.1.0` на Engine 8: + +```sh +composer require triangle/media:^1.1 +``` + +После публикации `2.0.0` для Engine 9: + +```sh +composer require triangle/media:^2.0 +``` + +Проверьте фактически выбранные версии: + +```sh +composer show triangle/media triangle/engine localzet/server +``` + +Плагин использует `view()` для HTML-маршрутов. Если они нужны, установите компонент `triangle/view` и добавьте шаблоны `index`, `form` и `image`. Если приложение отдаёт JSON или собственную страницу, замените эти контроллеры либо не открывайте соответствующие маршруты. + +## Установите конфигурацию + +Вызовите `Triangle\Media\Install::install()` в поддерживаемом lifecycle установки плагинов приложения. Он копирует отсутствующие файлы из `src/Config` в `config/plugin/triangle/media` и не перезаписывает уже существующие настройки. + +Для первого запуска проверьте: + +1. `image_path` указывает на доступный для записи каталог. +2. `image_uri` — публичный базовый URL с завершающим `/`. +3. `database.images` и `database.projects` совпадают с именами таблиц/коллекций вашего адаптера. +4. `project_registration` оставлен `false`, если приложению не нужна открытая регистрация. +5. Адаптеры `db()` и `storage()` соответствуют контрактам плагина. + +## Подключите маршруты + +Engine регистрирует контроллеры через Composer autoload. По умолчанию префикс плагинов — `/app`; проверьте `app.plugin_uri` в конфигурации приложения и настройте reverse proxy так, чтобы upload endpoint был доступен только через требуемую политику приложения. + +Встроенные HTML-маршруты требуют шаблоны представлений. Сам пакет не создаёт шаблоны, не настраивает веб-сервер и не публикует каталог хранения автоматически. + +## Проверьте запуск + +В каталоге пакета выполните локальные проверки: + +```sh +composer validate --strict --no-check-publish --no-interaction +composer run check --no-interaction +composer audit --locked --no-interaction +``` + +В тестовой среде должны быть доступны расширения из `composer.json`, включая `imagick`. Локальная проверка пакета не проверяет реальные маршруты, права каталога, базу данных, кэш и шаблоны вашего приложения. diff --git a/src/pages/projects/media/testing.mdx b/src/pages/projects/media/testing.mdx new file mode 100644 index 0000000..20ea146 --- /dev/null +++ b/src/pages/projects/media/testing.mdx @@ -0,0 +1,18 @@ +export const pageTitle = 'Triangle Media: тесты и ограничения' +export const description = 'Проверки Triangle Media, CI-матрица PHP и зависимостей, требования к ImageMagick и непокрытые интеграции приложения.' + +# Тесты и ограничения + +В репозитории объявлены `lint`, `test` и агрегирующая команда `check`: + +```sh +composer validate --strict --no-check-publish --no-interaction +composer run check --no-interaction +composer audit --locked --no-interaction +``` + +Набор включает проверки URL-загрузчика, регистрации проекта, контракта Engine request/file, отказа невалидных upload-объектов, MIME результата обработки, обхода каталогов и лимитов изображений. Integration-тест Imagick создаёт анимированный файл и проверяет число кадров, размеры фильтров и восстановление системных resource limits. + +GitHub Actions устанавливает `curl`, `intl`, `mbstring`, `pdo_sqlite` и `imagick`, проверяет PHP 8.1 и 8.5 на минимальном и актуальном допустимом наборе зависимостей, затем выполняет Composer audit, lint и тесты. + +Зелёный пакетный набор не заменяет интеграцию в приложении. Отдельно проверьте реальные database/storage adapters, маршруты Engine, templates, права `image_path`, proxy и фактические правила ImageMagick. Не выдавайте отсутствие advisory или успешный lint за проверку production-запуска. diff --git a/src/pages/projects/media/upload.mdx b/src/pages/projects/media/upload.mdx new file mode 100644 index 0000000..e357dd3 --- /dev/null +++ b/src/pages/projects/media/upload.mdx @@ -0,0 +1,67 @@ +export const pageTitle = 'Triangle Media: загрузка изображений' +export const description = 'Практическое руководство по multipart-загрузке, загрузке по ссылке, регистрации проекта и ответам API Triangle Media.' + +# Загрузка изображений + +Маршрут по умолчанию: `POST /app/media/upload`. Он принимает один из двух вариантов: multipart-файл в поле `file` или URL в поле `link`. В обоих случаях требуется токен проекта в поле `token`. + +## Получите токен проекта + +Маршрут регистрации `GET/POST /app/media/project` выключен настройкой `project_registration = false`. Включайте его только если приложение защищает маршрут авторизацией или другой подходящей политикой доступа. + +При включённой регистрации отправьте поля формы: + +```sh +curl -X POST 'https://app.example.test/app/media/project' \ + -H 'Accept: application/json' \ + -F 'name=My application' \ + -F 'description=Profile image uploads' \ + -F 'email=owner@example.test' +``` + +Ответ содержит сгенерированный `token`. Считайте его bearer-секретом. Если публичная регистрация не нужна, создайте запись проекта административным кодом приложения; поля и имя коллекции описаны в [контракте адаптера](/projects/media/configuration). + +## Загрузите локальный файл + +```sh +curl -X POST 'https://app.example.test/app/media/upload' \ + -H 'Accept: application/json' \ + -F 'token=PROJECT_TOKEN' \ + -F 'file=@./photo.jpg' +``` + +Не задавайте вручную `Content-Type` для multipart: curl добавляет границу формы. Плагин проверяет статус загруженного файла, его фактический MIME-тип и размер. MIME, присланный браузером, не считается доверенным источником. + +## Загрузите публичную ссылку + +```sh +curl -X POST 'https://app.example.test/app/media/upload' \ + -H 'Accept: application/json' \ + -F 'token=PROJECT_TOKEN' \ + -F 'link=https://images.example.test/photo.jpg' +``` + +Допустимы HTTP и HTTPS на стандартных портах. URL с userinfo, приватный/зарезервированный IP, непубличный DNS-ответ и redirect отклоняются. Ответ сервера ограничен размером `max_file_size` и таймаутом. + +## Ответ + +При `Accept: application/json` Engine обычно оборачивает ответ в объект со `status` и `data`. Полезная нагрузка успешной загрузки содержит: + +```json +{ + "message": "Image uploaded", + "id": "generated-image-id", + "url": "https://cdn.example.test/media/generated-image-id", + "mime": "image/png", + "width": 1200, + "height": 800, + "color": "#aabbcc", + "size": 84231 +} +``` + +Используйте `id` для маршрута [обработки изображения](/projects/media/processing). URL зависит от `image_uri`; это только адрес, который вернул плагин, он не настраивает CDN и web server. + +## Ошибки запроса + +Контроллер отклоняет неподдерживаемый метод, отсутствующие данные, неверный токен, невалидный файл, неверные поля проекта и запросы сверх rate limit. Типовые коды — 400, 403, 405, 422 и 429; итоговый HTTP status зависит также от `app.http_always_200` приложения. From 40b575d6ecdd49bff1dac9bd3bfc85c3ab028db9 Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Sat, 21 Nov 2026 01:10:34 +0300 Subject: [PATCH 2/5] docs: clarify TLS connection callback timing --- src/pages/current/security.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pages/current/security.mdx b/src/pages/current/security.mdx index e1ad3db..89468d7 100644 --- a/src/pages/current/security.mdx +++ b/src/pages/current/security.mdx @@ -54,9 +54,9 @@ export LOCALZET_SSL_CAFILE=/etc/localzet/client-ca.pem php server.php start ``` -Клиент предъявляет сертификат и ключ во время TLS handshake. Отсутствующий или недоверенный сертификат отклоняется до вызова обработчика приложения. Закрытый ключ сервера должен быть доступен только системной учётной записи сервиса; закрытые ключи клиентов передавайте через управляемое хранилище секретов. Проверка цепочки не устанавливает прикладные права: приложение должно отдельно определять, как проверенный сертификат соотносится с пользователем и его разрешениями. +Клиент предъявляет сертификат и ключ во время TLS handshake. Отсутствующий или недоверенный сертификат отклоняется до вызова обработчика приложения. На TLS listener `Server::$onConnect` вызывается только после успешного handshake; для обычного TCP listener он вызывается после принятия соединения. Закрытый ключ сервера должен быть доступен только системной учётной записи сервиса; закрытые ключи клиентов передавайте через управляемое хранилище секретов. Проверка цепочки не устанавливает прикладные права: приложение должно отдельно определять, как проверенный сертификат соотносится с пользователем и его разрешениями. -CI запускает локальную mTLS integration-проверку с краткоживущими тестовыми CA и сертификатами. Она проверяет доверенный, отсутствующий и недоверенный клиентский сертификат, а также то, что только доверенный клиент достигает HTTP callback-а. Это проверка механизма TLS в тестовом окружении, а не проверка production-конфигурации сертификатов. +CI запускает локальную mTLS integration-проверку с краткоживущими тестовыми CA и сертификатами. Она проверяет доверенный, отсутствующий и недоверенный клиентский сертификат, зависший TLS handshake, вызов `onConnect` только после успешного handshake и доступ только доверенного клиента к HTTP callback-у. Это проверка механизма TLS в тестовом окружении, а не проверка production-конфигурации сертификатов. ## TLS, сессии и gateway From 1748e27b5972a65345b5ef6bfb82b539191896a7 Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Sat, 21 Nov 2026 04:13:52 +0300 Subject: [PATCH 3/5] docs: sync Server 7.2.1 and Noter 0.1.12 --- README.md | 2 +- README.ru.md | 2 +- public/llms.txt | 6 +++--- src/components/Navigation.jsx | 2 +- src/pages/_app.jsx | 4 ++-- src/pages/api-ref/connection.mdx | 4 ++-- src/pages/api-ref/server.mdx | 2 +- src/pages/api-ref/timer.mdx | 2 +- src/pages/current/compatibility.mdx | 17 +++++++++++++---- src/pages/current/security.mdx | 2 +- src/pages/index.mdx | 8 ++++---- src/pages/projects/noter.mdx | 4 ++-- src/pages/projects/noter/reference.mdx | 4 ++-- 13 files changed, 34 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 7cc4ea0..04de9fd 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Open http://localhost:3000 during development. Build output is `out/`; the postb ## Documentation scope -The Server handbook describes the current stable release, 7.2.0. The project switcher also provides separate documentation areas for Cluster, Cron, HTTP Client, MQTT, PSR-7, Proxy, SOCKS5, Socket.IO, Storage, Tunnel, Noter, and Triangle Media. Each area has its own sidebar, search results, project metadata and compatibility notes. Media documents the published v1.1.0 Engine 8 package separately from the prepared but unreleased 2.0.0 Engine 9 migration. +The Server handbook describes the current stable release, 7.2.1. The project switcher also provides separate documentation areas for Cluster, Cron, HTTP Client, MQTT, PSR-7, Proxy, SOCKS5, Socket.IO, Storage, Tunnel, Noter, and Triangle Media. Each area has its own sidebar, search results, project metadata and compatibility notes. Media documents the published v1.1.0 Engine 8 package separately from the prepared but unreleased 2.0.0 Engine 9 migration. The AI-readable project map is available at [`public/llms.txt`](public/llms.txt); public pages are indexed in `public/sitemap.xml` and `public/robots.txt`. diff --git a/README.ru.md b/README.ru.md index bc0baca..67508ba 100644 --- a/README.ru.md +++ b/README.ru.md @@ -19,7 +19,7 @@ Dev-сайт открывается на http://localhost:3000. Результа ## Границы документации -Справочник Server описывает актуальный стабильный выпуск 7.2.0. Переключатель проектов открывает отдельную документацию Cluster, Cron, HTTP Client, MQTT, PSR-7, Proxy, SOCKS5, Socket.IO, Storage, Tunnel, Noter и Triangle Media. Для каждого проекта выделены собственная боковая навигация, поиск, метаданные и сведения о совместимости. Документация Media разделяет опубликованную v1.1.0 для Engine 8 и подготовку ещё не опубликованной версии 2.0.0 для Engine 9. +Справочник Server описывает актуальный стабильный выпуск 7.2.1. Переключатель проектов открывает отдельную документацию Cluster, Cron, HTTP Client, MQTT, PSR-7, Proxy, SOCKS5, Socket.IO, Storage, Tunnel, Noter и Triangle Media. Для каждого проекта выделены собственная боковая навигация, поиск, метаданные и сведения о совместимости. Документация Media разделяет опубликованную v1.1.0 для Engine 8 и подготовку ещё не опубликованной версии 2.0.0 для Engine 9. Старые страницы остаются в архиве, помечены предупреждением и исключены из поиска и sitemap. Справочник Server преимущественно русскоязычный; часть руководств связанных проектов доступна на русском и английском. Документация отражает проверенные исходники и статус релизов, но не заявляет production-готовность или поведение, не подтверждённое проверками. diff --git a/public/llms.txt b/public/llms.txt index 95726b0..bfd64fe 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -6,7 +6,7 @@ - Official documentation: https://server.localzet.com/ - Source repository: https://github.com/localzet/Server -- Current stable release: Localzet Server 7.2.0. Mutual TLS client-certificate verification can be configured through PHP TLS context options; CI covers trusted, missing, and untrusted client certificates. Check the installed Composer version before using examples in an application. +- Current stable release: Localzet Server 7.2.1. The TLS `onConnect` callback runs only after a successful handshake; plain TCP behavior is unchanged. Integration coverage includes trusted, missing, and untrusted client certificates. Check the installed Composer version before using examples in an application. - License: AGPL-3.0-or-later. - Runtime requirement: PHP 8.1 or newer with ext-json and ext-ctype. Unix multiprocess supervision requires pcntl and posix. @@ -61,12 +61,12 @@ Consider Localzet Server when a PHP application needs long-lived connections, cu - [Socket.IO](https://server.localzet.com/projects/socketio): release 2.0.2, in-memory adapter by default; Tunnel 3.x enables cross-process broadcast. Room subscriptions remain active while any local socket remains in the room. [Release notes](https://github.com/localzet/SocketIO/releases/tag/v2.0.2). - [Storage](https://server.localzet.com/projects/storage): release 1.0.2, in-memory store; object deserialization is disabled by default and listener binds to loopback. [Release notes](https://github.com/localzet/Storage/releases/tag/v1.0.2). - [Tunnel](https://server.localzet.com/projects/tunnel): release 3.0.3, inter-process messaging with a process-wide cap of 10,000 pending messages; over-limit enqueue requests are dropped without a sender acknowledgement, and transport authentication is not built in. [Release notes](https://github.com/localzet/Tunnel/releases/tag/v3.0.3). -- [Noter](https://server.localzet.com/projects/noter): release 0.1.11, PHP 8.4.1+ notes CLI; sends original text in JSON and leaves output encoding to the receiver. Its self-contained PHAR bundles Localzet HTTP 3.0.1, Console 2.2.1, PSR-7 4.0.0, and Server 7.2.0. [Release and PHAR](https://github.com/localzet/Noter/releases/tag/v0.1.11). +- [Noter](https://server.localzet.com/projects/noter): release 0.1.12, PHP 8.4.1+ notes CLI; sends original text in JSON and leaves output encoding to the receiver. Its self-contained PHAR bundles Localzet HTTP 3.0.1, Console 2.2.1, PSR-7 4.0.0, and Server 7.2.0. [Release and PHAR](https://github.com/localzet/Noter/releases/tag/v0.1.12). - [Triangle Media](https://server.localzet.com/projects/media): latest published tag `v1.1.0` requires Triangle Engine `^8.1`; the prepared major `2.0.0` targets Engine 9 and Server 7 but is not yet published. The guides cover installation, compatibility, configuration, uploads, ImageMagick filters, security, and tests in English and Russian. [Source](https://github.com/Triangle-org/Media), [migration status](https://github.com/Triangle-org/Media/pulls). ## Triangle Engine family -The current stable tags are Localzet Server 7.2.0, Triangle Engine 9.0.0, Router 2.0.6, and Middleware 2.0.3. Engine 9 requires Server `^7.1`, so the Server 7.2.0 tag satisfies its declared Composer constraint. Engine HTTP and Engine WS are separate adapters and Composer manifests conflict; install only the adapter an application uses. Check Composer's resolved versions in the application's lock file. +The current stable tags are Localzet Server 7.2.1, Triangle Engine 9.0.0, Router 2.0.6, and Middleware 2.0.3. Engine 9 requires Server `^7.1`, so the Server 7.2.1 tag satisfies its declared Composer constraint. Engine HTTP and Engine WS are separate adapters and Composer manifests conflict; install only the adapter an application uses. Check Composer's resolved versions in the application's lock file. - [Triangle Engine](https://server.localzet.com/projects/engine): release 9.0.0 for PHP 8.1+ and Localzet Server `^7.1`. [Requirements](https://server.localzet.com/projects/engine/requirements), [installation](https://server.localzet.com/projects/engine/install), [architecture](https://server.localzet.com/projects/engine/architecture), [compatibility with Engine 8](https://server.localzet.com/projects/engine/compatibility), and [test limits](https://server.localzet.com/projects/engine/testing). [Release notes](https://github.com/Triangle-org/Engine/releases/tag/v9.0.0). - [Triangle Engine HTTP](https://server.localzet.com/projects/engine-http): release 3.0.0 for Engine 9, Router 2, Middleware 2, Server 7.1+, PHP 8.1+, and ext-curl. Its install guide contains a runnable HTTP listener and curl check. CORS is disabled by default. [Compatibility](https://server.localzet.com/projects/engine-http/compatibility), [security](https://server.localzet.com/projects/engine-http/security), and [tests](https://server.localzet.com/projects/engine-http/testing). [Release notes](https://github.com/Triangle-org/Engine-HTTP/releases/tag/v3.0.0). diff --git a/src/components/Navigation.jsx b/src/components/Navigation.jsx index 9c767ef..65c8319 100644 --- a/src/components/Navigation.jsx +++ b/src/components/Navigation.jsx @@ -174,7 +174,7 @@ function NavigationGroup({group, className}) { const serverNavigation = [ { - title: 'Текущая версия · 7.2.0', + title: 'Текущая версия · 7.2.1', links: [ {title: 'Обзор и версия', href: '/'}, {title: 'Установка и первый сервер', href: '/current/start'}, diff --git a/src/pages/_app.jsx b/src/pages/_app.jsx index b11d833..7064987 100644 --- a/src/pages/_app.jsx +++ b/src/pages/_app.jsx @@ -11,7 +11,7 @@ import '@/styles/tailwind.css' import 'focus-visible' const SITE_URL = 'https://server.localzet.com' -const DEFAULT_TITLE = 'Localzet Server 7.2.0 — документация' +const DEFAULT_TITLE = 'Localzet Server 7.2.1 — документация' const DEFAULT_DESCRIPTION = 'Официальная документация Localzet Server: асинхронный PHP runtime для HTTP/1.x, WebSocket, TCP и UDP, с event loop и управлением worker-процессами.' const CLUSTER_TITLE = 'Localzet Cluster — документация' const CLUSTER_DESCRIPTION = 'Документация Localzet Cluster: распределённая архитектура Gateway/Business Worker для приложений на PHP, регистрация узлов и маршрутизация клиентских соединений.' @@ -156,7 +156,7 @@ export default function App({Component, pageProps}) { runtimePlatform: 'PHP 8.1 or newer', version: cluster ? 'current Cluster source, requires Server ^7.0' - : relatedProject?.[3] ?? (relatedProject ? 'current repository source' : '7.2.0'), + : relatedProject?.[3] ?? (relatedProject ? 'current repository source' : '7.2.1'), license: 'https://spdx.org/licenses/AGPL-3.0-or-later.html', author: { '@type': 'Person', diff --git a/src/pages/api-ref/connection.mdx b/src/pages/api-ref/connection.mdx index f878288..2eac650 100644 --- a/src/pages/api-ref/connection.mdx +++ b/src/pages/api-ref/connection.mdx @@ -1,4 +1,4 @@ -export const pageTitle = 'API: TcpConnection 7.2.0' +export const pageTitle = 'API: TcpConnection 7.2.1' export const description = 'Справочник TcpConnection и ConnectionInterface Localzet Server: отправка данных, callbacks, buffering и управление соединением.' # API: `TcpConnection` @@ -28,7 +28,7 @@ export const description = 'Справочник TcpConnection и ConnectionInte ## Callback-и соединения -На instance можно задать `onMessage`, `onClose`, `onError`, `onBufferFull` и `onBufferDrain`. WebSocket connection дополнительно имеет callbacks handshake, ping/pong и close. Проверяйте типы и сигнатуры в исходном `TcpConnection.php`/`ConnectionInterface.php`; эти классы — актуальный контракт текущей версии 7.2.0. +На instance можно задать `onMessage`, `onClose`, `onError`, `onBufferFull` и `onBufferDrain`. WebSocket connection дополнительно имеет callbacks handshake, ping/pong и close. Проверяйте типы и сигнатуры в исходном `TcpConnection.php`/`ConnectionInterface.php`; эти классы — актуальный контракт текущей версии 7.2.1. ## Асинхронный клиент diff --git a/src/pages/api-ref/server.mdx b/src/pages/api-ref/server.mdx index be461a2..df4e3b0 100644 --- a/src/pages/api-ref/server.mdx +++ b/src/pages/api-ref/server.mdx @@ -1,4 +1,4 @@ -export const pageTitle = 'API: Server 7.2.0' +export const pageTitle = 'API: Server 7.2.1' export const description = 'Справочник класса localzet\\Server: listener-ы, callbacks, параметры worker-ов и lifecycle API.' # API: `localzet\Server` diff --git a/src/pages/api-ref/timer.mdx b/src/pages/api-ref/timer.mdx index 6c3c97b..1696c2d 100644 --- a/src/pages/api-ref/timer.mdx +++ b/src/pages/api-ref/timer.mdx @@ -1,4 +1,4 @@ -export const pageTitle = 'API: Timer 7.2.0' +export const pageTitle = 'API: Timer 7.2.1' export const description = 'Справочник localzet\\Timer: repeat, delay, удаление и особенности сна в разных event loop backend-ах.' # API: `localzet\Timer` diff --git a/src/pages/current/compatibility.mdx b/src/pages/current/compatibility.mdx index c457188..4c82bb9 100644 --- a/src/pages/current/compatibility.mdx +++ b/src/pages/current/compatibility.mdx @@ -1,9 +1,18 @@ export const pageTitle = 'Совместимость и сравнение версий' -export const description = 'Совместимость Localzet Server 7.2.0, настройка взаимной проверки TLS-сертификатов, исправления lifecycle и сравнение с предыдущими выпусками.' +export const description = 'Совместимость Localzet Server 7.2.1, изменения TLS callback, настройка взаимной проверки сертификатов и сравнение версий.' # Совместимость и сравнение версий -Последний выпуск — `v7.2.0`. Устанавливайте его через `composer require localzet/server:^7.2`. Пакеты `^7.0` также допускают обновление в пределах Server 7; перед развёртыванием сверяйте выбранную версию через `composer show localzet/server`. +Последний выпуск — `v7.2.1`. Устанавливайте его через `composer require localzet/server:^7.2`. Пакеты `^7.0` также допускают обновление в пределах Server 7; перед развёртыванием сверяйте выбранную версию через `composer show localzet/server`. + +### Изменения в выпуске 7.2.1 + +| Область | Server 7.2.0 | Server 7.2.1 | +|---|---|---| +| TLS `onConnect` | Callback мог вызываться до завершения TLS handshake | Callback вызывается после успешного handshake; для неуспешного handshake callback не запускается | +| Обычный TCP | Callback вызывается после подключения | Поведение не изменилось | + +Проверка включает mTLS-сценарии с доверенным, отсутствующим и недоверенным клиентским сертификатом. Приложениям, которые полагались на вызов TLS `onConnect` до завершения handshake, следует проверить эту логику с новым порядком вызова. ### Изменения в выпуске 7.2.0 @@ -38,7 +47,7 @@ PHP 8.1–8.3 остаются поддерживаемыми для обычн Ниже сравниваются исходники текущего выпуска с тегом `v4.5.3`. Это сравнение исходного кода и манифестов, а не гарантия совместимости конкретного приложения. -| Область | `v4.5.3` | Текущий выпуск `v7.2.0` | +| Область | `v4.5.3` | Текущий выпуск `v7.2.1` | |---|---|---| | PHP и обязательные зависимости | PHP `^8.1 \|\| ^8.2`; обязательны `ext-sockets`, `ext-pcntl`, `ext-posix`, `localzet/events` | PHP `>=8.1`; обязательны `ext-json` и `ext-ctype`; остальные интеграции объявлены как optional | | Event loop | Собственный набор Linux drivers, включая `StreamSelect`, `ext-uv`, `ext-event` и `ext-ev` | `EventLoopFactory`: `event` → `ev` → Revolt → встроенный `Select`; Windows имеет отдельную реализацию, Swoole/Swow выбираются явно | @@ -46,7 +55,7 @@ PHP 8.1–8.3 остаются поддерживаемыми для обычн | Hot upgrade | В исходниках тега нет `Runtime/HotUpgradeBroker` | Unix hot upgrade сохраняет listener descriptors; требуется PHP 8.4+ с нужной поддержкой socket flags | | Публичный API | Сигнатуры и реализация отражают контракт тега 4.5.3 | API и runtime изменялись; используйте справочник текущей версии и проверяйте приложение тестами | -Ссылки на исходники: [`v4.5.3` composer.json](https://github.com/localzet/Server/blob/v4.5.3/composer.json), [`v7.2.0` composer.json](https://github.com/localzet/Server/blob/v7.2.0/composer.json), [сравнение тегов](https://github.com/localzet/Server/compare/v4.5.3...v7.2.0), [изменения 7.1.0 → 7.2.0](https://github.com/localzet/Server/compare/v7.1.0...v7.2.0). +Ссылки на исходники: [`v4.5.3` composer.json](https://github.com/localzet/Server/blob/v4.5.3/composer.json), [`v7.2.1` composer.json](https://github.com/localzet/Server/blob/v7.2.1/composer.json), [сравнение тегов](https://github.com/localzet/Server/compare/v4.5.3...v7.2.1), [изменения 7.2.0 → 7.2.1](https://github.com/localzet/Server/compare/v7.2.0...v7.2.1). ## Перед обновлением приложения diff --git a/src/pages/current/security.mdx b/src/pages/current/security.mdx index 89468d7..cf7cb2e 100644 --- a/src/pages/current/security.mdx +++ b/src/pages/current/security.mdx @@ -1,5 +1,5 @@ export const pageTitle = 'Модель безопасности и границы доверия' -export const description = 'Модель доверия Localzet Server 7.2.0: защита HTTP parser, trusted proxies, TLS, PID/runtime-файлы, права worker-ов, sessions и gateway.' +export const description = 'Модель доверия Localzet Server 7.2.1: защита HTTP parser, trusted proxies, TLS, PID/runtime-файлы, права worker-ов, sessions и gateway.' # Модель безопасности diff --git a/src/pages/index.mdx b/src/pages/index.mdx index 9c03b6d..db8090e 100644 --- a/src/pages/index.mdx +++ b/src/pages/index.mdx @@ -1,13 +1,13 @@ import {HeroPattern} from '@/components/HeroPattern' -export const pageTitle = 'Localzet Server 7.2.0 — документация и руководство' -export const description = 'Официальная документация Localzet Server 7.2.0: PHP runtime для HTTP/1.x, WebSocket, TCP и UDP, event loop, worker-процессов и управления жизненным циклом.' +export const pageTitle = 'Localzet Server 7.2.1 — документация и руководство' +export const description = 'Официальная документация Localzet Server 7.2.1: PHP runtime для HTTP/1.x, WebSocket, TCP и UDP, event loop, worker-процессов и управления жизненным циклом.' # Localzet Server -Последняя опубликованная версия Localzet Server — **7.2.0**. Это PHP-библиотека для серверных приложений с долгоживущими соединениями, несколькими сетевыми протоколами и управлением worker-процессами. Для перехода с предыдущего выпуска смотрите [сравнение версий и изменений поведения](/current/compatibility). +Последняя опубликованная версия Localzet Server — **7.2.1**. Это PHP-библиотека для серверных приложений с долгоживущими соединениями, несколькими сетевыми протоколами и управлением worker-процессами. Для перехода с предыдущего выпуска смотрите [сравнение версий и изменений поведения](/current/compatibility). Пакет `localzet/server:^7.1` устанавливается через Composer. Проверяйте фактически выбранную версию командой `composer show localzet/server`; таблица [совместимости](/current/compatibility) описывает требования и изменения при переходе с предыдущих выпусков. @@ -45,4 +45,4 @@ export const description = 'Официальная документация Loca Сервер реализует HTTP/1.x, TLS поверх PHP streams, WebSocket, TCP и UDP. Gateway включает raw TCP proxy и потоковый HTTP/1.x reverse proxy с WebSocket Upgrade. Он не является HTTP/2/3 ingress, API management платформой или системой service discovery. В проекте нет встроенной аутентификации приложения, rate limiter или гарантии производительности для произвольной нагрузки. -Справочные страницы, которые не входят в текущую документацию, помечены как архивные. Для актуального кода начинайте с раздела **Версия 7.2.0** в меню. +Справочные страницы, которые не входят в текущую документацию, помечены как архивные. Для актуального кода начинайте с раздела **Версия 7.2.1** в меню. diff --git a/src/pages/projects/noter.mdx b/src/pages/projects/noter.mdx index 9500f3a..6ff1c1d 100644 --- a/src/pages/projects/noter.mdx +++ b/src/pages/projects/noter.mdx @@ -1,11 +1,11 @@ export const pageTitle = 'Noter' -export const description = 'Консольная утилита для создания и управления заметками с серверной частью на Localzet HTTP.' +export const description = 'CLI-клиент для отправки заметок на HTTP(S)-приёмник с конфигурацией и готовым PHAR.' # Noter [Начало работы](/projects/noter/start) · [API и эксплуатация](/projects/noter/reference) -Noter — PHP CLI-проект для отправки заметок на HTTP(S)-приёмник. Выпуск [`v0.1.11`](https://github.com/localzet/Noter/releases/tag/v0.1.11) требует PHP 8.4.1+ и cURL, использует `localzet/http:^3.0`, `localzet/psr7:^4.0` и `localzet/console:^2.0`. PHAR включает зависимости из lockfile: Localzet HTTP 3.0.1, Console 2.2.1, PSR-7 4.0.0 и Server 7.2.0. GitHub Release прикладывает self-contained PHAR; исходники и журнал версий доступны в [репозитории Noter](https://github.com/localzet/Noter). +Noter — PHP CLI-проект для отправки заметок на HTTP(S)-приёмник. Выпуск [`v0.1.12`](https://github.com/localzet/Noter/releases/tag/v0.1.12) требует PHP 8.4.1+ и cURL, использует `localzet/http:^3.0`, `localzet/psr7:^4.0` и `localzet/console:^2.0`. PHAR включает зависимости из lockfile: Localzet HTTP 3.0.1, Console 2.2.1, PSR-7 4.0.0 и Server 7.2.0. GitHub Release прикладывает self-contained PHAR; исходники и журнал версий доступны в [репозитории Noter](https://github.com/localzet/Noter). ```sh composer install diff --git a/src/pages/projects/noter/reference.mdx b/src/pages/projects/noter/reference.mdx index d5d9787..522f3dd 100644 --- a/src/pages/projects/noter/reference.mdx +++ b/src/pages/projects/noter/reference.mdx @@ -3,7 +3,7 @@ export const description = 'Формат HTTP запроса, конфигура # Noter: API и эксплуатация -Noter — CLI отправитель заметок, а не приложение-хранилище. В версии [`v0.1.11`](https://github.com/localzet/Noter/releases/tag/v0.1.11) требуются PHP 8.4.1+ и `ext-curl`. Команда `noter ` берёт текст из аргумента; при отсутствии аргумента читает stdin. +Noter — CLI отправитель заметок, а не приложение-хранилище. В версии [`v0.1.12`](https://github.com/localzet/Noter/releases/tag/v0.1.12) требуются PHP 8.4.1+ и `ext-curl`. Команда `noter ` берёт текст из аргумента; при отсутствии аргумента читает stdin. ## Контракт приёмника @@ -25,4 +25,4 @@ CLI выполняет HTTP POST на `NOTER_URL` и отправляет: ## Зависимости и release -Lockfile версии `v0.1.11` фиксирует `localzet/http 3.0.1`, `localzet/psr7 4.0.0`, `localzet/console 2.2.1`, `illuminate/console 13.43.0`, `symfony/console 8.1.11` и `localzet/server 7.2.0`. CI проверяет Composer manifest/lock, lint, PHAR и loopback HTTP сценарии. GitHub Release прикладывает self-contained `noter.phar`; для запуска требуется PHP CLI 8.4.1+ с cURL. +Lockfile версии `v0.1.12` фиксирует `localzet/http 3.0.1`, `localzet/psr7 4.0.0`, `localzet/console 2.2.1`, `illuminate/console 13.43.0`, `symfony/console 8.1.11` и `localzet/server 7.2.0`. CI проверяет Composer manifest/lock, lint, PHAR и loopback HTTP сценарии. GitHub Release прикладывает self-contained `noter.phar`; для запуска требуется PHP CLI 8.4.1+ с cURL. From 1756b47a1544fa7ef8772cd500b4c4489c55af19 Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Sat, 21 Nov 2026 12:44:55 +0300 Subject: [PATCH 4/5] docs: expand Triangle guides and refresh versions --- public/llms.txt | 21 +- public/sitemap.xml | 550 ++++++++++++++++++ src/components/Header.jsx | 65 ++- src/components/Navigation.jsx | 58 +- src/pages/_app.jsx | 139 ++++- src/pages/projects/mqtt.mdx | 2 +- src/pages/projects/storage.mdx | 9 +- src/pages/projects/storage/reference.mdx | 4 +- src/pages/projects/storage/start.mdx | 6 +- src/pages/projects/triangle-console.mdx | 52 ++ .../triangle-console/compatibility.mdx | 23 + src/pages/projects/triangle-console/en.mdx | 52 ++ .../triangle-console/en/compatibility.mdx | 23 + .../projects/triangle-console/en/install.mdx | 19 + .../triangle-console/en/operations.mdx | 14 + .../projects/triangle-console/en/usage.mdx | 43 ++ .../projects/triangle-console/install.mdx | 19 + .../projects/triangle-console/operations.mdx | 14 + src/pages/projects/triangle-console/usage.mdx | 43 ++ src/pages/projects/triangle-cron.mdx | 48 ++ .../projects/triangle-cron/compatibility.mdx | 16 + src/pages/projects/triangle-cron/en.mdx | 48 ++ .../triangle-cron/en/compatibility.mdx | 16 + .../projects/triangle-cron/en/install.mdx | 15 + .../projects/triangle-cron/en/operations.mdx | 8 + src/pages/projects/triangle-cron/en/usage.mdx | 23 + src/pages/projects/triangle-cron/install.mdx | 15 + .../projects/triangle-cron/operations.mdx | 8 + src/pages/projects/triangle-cron/usage.mdx | 23 + src/pages/projects/triangle-database.mdx | 56 ++ .../triangle-database/compatibility.mdx | 14 + src/pages/projects/triangle-database/en.mdx | 56 ++ .../triangle-database/en/compatibility.mdx | 14 + .../projects/triangle-database/en/install.mdx | 27 + .../triangle-database/en/operations.mdx | 10 + .../projects/triangle-database/en/usage.mdx | 30 + .../projects/triangle-database/install.mdx | 27 + .../projects/triangle-database/operations.mdx | 10 + .../projects/triangle-database/usage.mdx | 30 + src/pages/projects/triangle-events.mdx | 25 + .../triangle-events/compatibility.mdx | 34 ++ src/pages/projects/triangle-events/en.mdx | 25 + .../triangle-events/en/compatibility.mdx | 34 ++ .../projects/triangle-events/en/install.mdx | 59 ++ .../triangle-events/en/operations.mdx | 30 + .../projects/triangle-events/en/usage.mdx | 41 ++ .../projects/triangle-events/install.mdx | 59 ++ .../projects/triangle-events/operations.mdx | 30 + src/pages/projects/triangle-events/usage.mdx | 41 ++ src/pages/projects/triangle-middleware.mdx | 54 ++ .../triangle-middleware/compatibility.mdx | 16 + src/pages/projects/triangle-middleware/en.mdx | 54 ++ .../triangle-middleware/en/compatibility.mdx | 16 + .../triangle-middleware/en/install.mdx | 15 + .../triangle-middleware/en/operations.mdx | 10 + .../projects/triangle-middleware/en/usage.mdx | 32 + .../projects/triangle-middleware/install.mdx | 15 + .../triangle-middleware/operations.mdx | 10 + .../projects/triangle-middleware/usage.mdx | 32 + src/pages/projects/triangle-oauth.mdx | 59 ++ .../projects/triangle-oauth/compatibility.mdx | 23 + src/pages/projects/triangle-oauth/en.mdx | 59 ++ .../triangle-oauth/en/compatibility.mdx | 23 + .../projects/triangle-oauth/en/install.mdx | 27 + .../projects/triangle-oauth/en/operations.mdx | 20 + .../projects/triangle-oauth/en/usage.mdx | 40 ++ src/pages/projects/triangle-oauth/install.mdx | 27 + .../projects/triangle-oauth/operations.mdx | 20 + src/pages/projects/triangle-oauth/usage.mdx | 40 ++ src/pages/projects/triangle-router.mdx | 15 + .../triangle-router/compatibility.mdx | 30 + src/pages/projects/triangle-router/en.mdx | 15 + .../triangle-router/en/compatibility.mdx | 30 + .../projects/triangle-router/en/install.mdx | 44 ++ .../triangle-router/en/operations.mdx | 32 + .../projects/triangle-router/en/usage.mdx | 33 ++ .../projects/triangle-router/install.mdx | 44 ++ .../projects/triangle-router/operations.mdx | 32 + src/pages/projects/triangle-router/usage.mdx | 33 ++ src/pages/projects/triangle-session.mdx | 42 ++ .../triangle-session/compatibility.mdx | 13 + src/pages/projects/triangle-session/en.mdx | 42 ++ .../triangle-session/en/compatibility.mdx | 13 + .../projects/triangle-session/en/install.mdx | 15 + .../triangle-session/en/operations.mdx | 10 + .../projects/triangle-session/en/usage.mdx | 17 + .../projects/triangle-session/install.mdx | 15 + .../projects/triangle-session/operations.mdx | 10 + src/pages/projects/triangle-session/usage.mdx | 17 + src/pages/projects/triangle-view.mdx | 15 + .../projects/triangle-view/compatibility.mdx | 30 + src/pages/projects/triangle-view/en.mdx | 15 + .../triangle-view/en/compatibility.mdx | 30 + .../projects/triangle-view/en/install.mdx | 37 ++ .../projects/triangle-view/en/operations.mdx | 32 + src/pages/projects/triangle-view/en/usage.mdx | 29 + src/pages/projects/triangle-view/install.mdx | 38 ++ .../projects/triangle-view/operations.mdx | 32 + src/pages/projects/triangle-view/usage.mdx | 29 + src/pages/projects/triangle-web.mdx | 47 ++ .../projects/triangle-web/compatibility.mdx | 13 + src/pages/projects/triangle-web/en.mdx | 47 ++ .../triangle-web/en/compatibility.mdx | 13 + .../projects/triangle-web/en/install.mdx | 14 + .../projects/triangle-web/en/operations.mdx | 10 + src/pages/projects/triangle-web/en/usage.mdx | 20 + src/pages/projects/triangle-web/install.mdx | 14 + .../projects/triangle-web/operations.mdx | 10 + src/pages/projects/triangle-web/usage.mdx | 20 + src/pages/projects/triangle-ws.mdx | 34 ++ .../projects/triangle-ws/compatibility.mdx | 8 + src/pages/projects/triangle-ws/en.mdx | 34 ++ .../projects/triangle-ws/en/compatibility.mdx | 8 + src/pages/projects/triangle-ws/en/install.mdx | 14 + .../projects/triangle-ws/en/operations.mdx | 10 + src/pages/projects/triangle-ws/en/usage.mdx | 18 + src/pages/projects/triangle-ws/install.mdx | 14 + src/pages/projects/triangle-ws/operations.mdx | 10 + src/pages/projects/triangle-ws/usage.mdx | 18 + src/pages/projects/tunnel.mdx | 8 +- src/pages/projects/tunnel/reference.mdx | 8 +- src/pages/projects/tunnel/start.mdx | 4 +- 122 files changed, 3745 insertions(+), 60 deletions(-) create mode 100644 src/pages/projects/triangle-console.mdx create mode 100644 src/pages/projects/triangle-console/compatibility.mdx create mode 100644 src/pages/projects/triangle-console/en.mdx create mode 100644 src/pages/projects/triangle-console/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-console/en/install.mdx create mode 100644 src/pages/projects/triangle-console/en/operations.mdx create mode 100644 src/pages/projects/triangle-console/en/usage.mdx create mode 100644 src/pages/projects/triangle-console/install.mdx create mode 100644 src/pages/projects/triangle-console/operations.mdx create mode 100644 src/pages/projects/triangle-console/usage.mdx create mode 100644 src/pages/projects/triangle-cron.mdx create mode 100644 src/pages/projects/triangle-cron/compatibility.mdx create mode 100644 src/pages/projects/triangle-cron/en.mdx create mode 100644 src/pages/projects/triangle-cron/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-cron/en/install.mdx create mode 100644 src/pages/projects/triangle-cron/en/operations.mdx create mode 100644 src/pages/projects/triangle-cron/en/usage.mdx create mode 100644 src/pages/projects/triangle-cron/install.mdx create mode 100644 src/pages/projects/triangle-cron/operations.mdx create mode 100644 src/pages/projects/triangle-cron/usage.mdx create mode 100644 src/pages/projects/triangle-database.mdx create mode 100644 src/pages/projects/triangle-database/compatibility.mdx create mode 100644 src/pages/projects/triangle-database/en.mdx create mode 100644 src/pages/projects/triangle-database/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-database/en/install.mdx create mode 100644 src/pages/projects/triangle-database/en/operations.mdx create mode 100644 src/pages/projects/triangle-database/en/usage.mdx create mode 100644 src/pages/projects/triangle-database/install.mdx create mode 100644 src/pages/projects/triangle-database/operations.mdx create mode 100644 src/pages/projects/triangle-database/usage.mdx create mode 100644 src/pages/projects/triangle-events.mdx create mode 100644 src/pages/projects/triangle-events/compatibility.mdx create mode 100644 src/pages/projects/triangle-events/en.mdx create mode 100644 src/pages/projects/triangle-events/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-events/en/install.mdx create mode 100644 src/pages/projects/triangle-events/en/operations.mdx create mode 100644 src/pages/projects/triangle-events/en/usage.mdx create mode 100644 src/pages/projects/triangle-events/install.mdx create mode 100644 src/pages/projects/triangle-events/operations.mdx create mode 100644 src/pages/projects/triangle-events/usage.mdx create mode 100644 src/pages/projects/triangle-middleware.mdx create mode 100644 src/pages/projects/triangle-middleware/compatibility.mdx create mode 100644 src/pages/projects/triangle-middleware/en.mdx create mode 100644 src/pages/projects/triangle-middleware/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-middleware/en/install.mdx create mode 100644 src/pages/projects/triangle-middleware/en/operations.mdx create mode 100644 src/pages/projects/triangle-middleware/en/usage.mdx create mode 100644 src/pages/projects/triangle-middleware/install.mdx create mode 100644 src/pages/projects/triangle-middleware/operations.mdx create mode 100644 src/pages/projects/triangle-middleware/usage.mdx create mode 100644 src/pages/projects/triangle-oauth.mdx create mode 100644 src/pages/projects/triangle-oauth/compatibility.mdx create mode 100644 src/pages/projects/triangle-oauth/en.mdx create mode 100644 src/pages/projects/triangle-oauth/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-oauth/en/install.mdx create mode 100644 src/pages/projects/triangle-oauth/en/operations.mdx create mode 100644 src/pages/projects/triangle-oauth/en/usage.mdx create mode 100644 src/pages/projects/triangle-oauth/install.mdx create mode 100644 src/pages/projects/triangle-oauth/operations.mdx create mode 100644 src/pages/projects/triangle-oauth/usage.mdx create mode 100644 src/pages/projects/triangle-router.mdx create mode 100644 src/pages/projects/triangle-router/compatibility.mdx create mode 100644 src/pages/projects/triangle-router/en.mdx create mode 100644 src/pages/projects/triangle-router/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-router/en/install.mdx create mode 100644 src/pages/projects/triangle-router/en/operations.mdx create mode 100644 src/pages/projects/triangle-router/en/usage.mdx create mode 100644 src/pages/projects/triangle-router/install.mdx create mode 100644 src/pages/projects/triangle-router/operations.mdx create mode 100644 src/pages/projects/triangle-router/usage.mdx create mode 100644 src/pages/projects/triangle-session.mdx create mode 100644 src/pages/projects/triangle-session/compatibility.mdx create mode 100644 src/pages/projects/triangle-session/en.mdx create mode 100644 src/pages/projects/triangle-session/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-session/en/install.mdx create mode 100644 src/pages/projects/triangle-session/en/operations.mdx create mode 100644 src/pages/projects/triangle-session/en/usage.mdx create mode 100644 src/pages/projects/triangle-session/install.mdx create mode 100644 src/pages/projects/triangle-session/operations.mdx create mode 100644 src/pages/projects/triangle-session/usage.mdx create mode 100644 src/pages/projects/triangle-view.mdx create mode 100644 src/pages/projects/triangle-view/compatibility.mdx create mode 100644 src/pages/projects/triangle-view/en.mdx create mode 100644 src/pages/projects/triangle-view/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-view/en/install.mdx create mode 100644 src/pages/projects/triangle-view/en/operations.mdx create mode 100644 src/pages/projects/triangle-view/en/usage.mdx create mode 100644 src/pages/projects/triangle-view/install.mdx create mode 100644 src/pages/projects/triangle-view/operations.mdx create mode 100644 src/pages/projects/triangle-view/usage.mdx create mode 100644 src/pages/projects/triangle-web.mdx create mode 100644 src/pages/projects/triangle-web/compatibility.mdx create mode 100644 src/pages/projects/triangle-web/en.mdx create mode 100644 src/pages/projects/triangle-web/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-web/en/install.mdx create mode 100644 src/pages/projects/triangle-web/en/operations.mdx create mode 100644 src/pages/projects/triangle-web/en/usage.mdx create mode 100644 src/pages/projects/triangle-web/install.mdx create mode 100644 src/pages/projects/triangle-web/operations.mdx create mode 100644 src/pages/projects/triangle-web/usage.mdx create mode 100644 src/pages/projects/triangle-ws.mdx create mode 100644 src/pages/projects/triangle-ws/compatibility.mdx create mode 100644 src/pages/projects/triangle-ws/en.mdx create mode 100644 src/pages/projects/triangle-ws/en/compatibility.mdx create mode 100644 src/pages/projects/triangle-ws/en/install.mdx create mode 100644 src/pages/projects/triangle-ws/en/operations.mdx create mode 100644 src/pages/projects/triangle-ws/en/usage.mdx create mode 100644 src/pages/projects/triangle-ws/install.mdx create mode 100644 src/pages/projects/triangle-ws/operations.mdx create mode 100644 src/pages/projects/triangle-ws/usage.mdx diff --git a/public/llms.txt b/public/llms.txt index bfd64fe..f54e5df 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -54,19 +54,19 @@ Consider Localzet Server when a PHP application needs long-lived connections, cu - [Cron](https://server.localzet.com/projects/cron): release 2.0.1, timer-based scheduling for Server 7; removing a job cancels its pending one-shot timers. [Release notes](https://github.com/localzet/Cron/releases/tag/v2.0.1). - [Console](https://server.localzet.com/projects/console): release 2.2.1, PHP CLI library with Symfony Console by default, an opt-in Laravel command bridge, Unicode/ANSI helpers and bounded terminal dashboards. Requires PHP 8.4.1+. [Release notes](https://github.com/localzet/Console/releases/tag/v2.2.1). - [HTTP Client](https://server.localzet.com/projects/httpclient): release 3.0.1, asynchronous HTTP requests and connection pooling for Server 7; verifies TLS peers by default and strips sensitive headers on cross-origin redirects. [Release notes](https://github.com/localzet/HttpClient/releases/tag/v3.0.1). -- [MQTT](https://server.localzet.com/projects/mqtt): release 1.0.1, MQTT 3.1.1 and MQTT 5 client with TCP/TLS, QoS 0/1/2, and legacy Server protocol aliases. [Release notes](https://github.com/localzet/MQTT/releases/tag/v1.0.1). +- [MQTT](https://server.localzet.com/projects/mqtt): release 1.0.2, MQTT 3.1.1 and MQTT 5 client with TCP/TLS, QoS 0/1/2, and legacy Server protocol aliases; debug logs redact credentials, topics, properties, and payloads. [Release notes](https://github.com/localzet/MQTT/releases/tag/v1.0.2). - [PSR-7](https://server.localzet.com/projects/psr7): release 4.0.0, HTTP messages, streams and URI helpers for Server 7. [Release notes](https://github.com/localzet/PSR-7/releases/tag/v4.0.0). - [Proxy](https://server.localzet.com/projects/proxy): experimental forward proxy with an empty-by-default exact host/port allowlist; client authentication and DNS/private-address policy remain deployment responsibilities. - [SOCKS5](https://server.localzet.com/projects/socks5): release 1.0.0, TCP CONNECT proxy; default configuration binds to loopback. [Release notes](https://github.com/localzet/SOCKS5/releases/tag/v1.0.0). -- [Socket.IO](https://server.localzet.com/projects/socketio): release 2.0.2, in-memory adapter by default; Tunnel 3.x enables cross-process broadcast. Room subscriptions remain active while any local socket remains in the room. [Release notes](https://github.com/localzet/SocketIO/releases/tag/v2.0.2). -- [Storage](https://server.localzet.com/projects/storage): release 1.0.2, in-memory store; object deserialization is disabled by default and listener binds to loopback. [Release notes](https://github.com/localzet/Storage/releases/tag/v1.0.2). -- [Tunnel](https://server.localzet.com/projects/tunnel): release 3.0.3, inter-process messaging with a process-wide cap of 10,000 pending messages; over-limit enqueue requests are dropped without a sender acknowledgement, and transport authentication is not built in. [Release notes](https://github.com/localzet/Tunnel/releases/tag/v3.0.3). +- [Socket.IO](https://server.localzet.com/projects/socketio): release 2.0.2, in-memory adapter by default; its documented cross-process adapter targets Tunnel 3.x, and compatibility with Tunnel 4 has not been verified. Room subscriptions remain active while any local socket remains in the room. [Release notes](https://github.com/localzet/SocketIO/releases/tag/v2.0.2). +- [Storage](https://server.localzet.com/projects/storage): release 2.0.0, PHP 8.2+ in-memory store for Server 7; rejects objects and recursive arrays by default, limits frames to 64 MiB, and must be installed from the Git VCS source because it is not on Packagist. [Release notes](https://github.com/localzet/Storage/releases/tag/v2.0.0). +- [Tunnel](https://server.localzet.com/projects/tunnel): release 4.0.1, inter-process messaging with process-wide limits of 10,000 pending queue messages and 32 MiB of queued request bytes; objects and recursive arrays are rejected by default. Debug logs redact message payloads and raw exceptions. Over-limit enqueue is rejected without acknowledgement, and transport authentication is not built in. [Release notes](https://github.com/localzet/Tunnel/releases/tag/v4.0.1). - [Noter](https://server.localzet.com/projects/noter): release 0.1.12, PHP 8.4.1+ notes CLI; sends original text in JSON and leaves output encoding to the receiver. Its self-contained PHAR bundles Localzet HTTP 3.0.1, Console 2.2.1, PSR-7 4.0.0, and Server 7.2.0. [Release and PHAR](https://github.com/localzet/Noter/releases/tag/v0.1.12). - [Triangle Media](https://server.localzet.com/projects/media): latest published tag `v1.1.0` requires Triangle Engine `^8.1`; the prepared major `2.0.0` targets Engine 9 and Server 7 but is not yet published. The guides cover installation, compatibility, configuration, uploads, ImageMagick filters, security, and tests in English and Russian. [Source](https://github.com/Triangle-org/Media), [migration status](https://github.com/Triangle-org/Media/pulls). ## Triangle Engine family -The current stable tags are Localzet Server 7.2.1, Triangle Engine 9.0.0, Router 2.0.6, and Middleware 2.0.3. Engine 9 requires Server `^7.1`, so the Server 7.2.1 tag satisfies its declared Composer constraint. Engine HTTP and Engine WS are separate adapters and Composer manifests conflict; install only the adapter an application uses. Check Composer's resolved versions in the application's lock file. +The current stable tags are Localzet Server 7.2.1, Triangle Engine 9.0.0, Router 2.0.7, Middleware 2.0.3, Console 2.0.0, Database 2.0.0, Session 2.0.0, Events 2.0.1, and View 2.1.0. Engine 9 requires Server `^7.1`, so the Server 7.2.1 tag satisfies its declared Composer constraint. Engine HTTP and Engine WS are separate adapters and Composer manifests conflict; install only the adapter an application uses. Check Composer's resolved versions in the application's lock file. - [Triangle Engine](https://server.localzet.com/projects/engine): release 9.0.0 for PHP 8.1+ and Localzet Server `^7.1`. [Requirements](https://server.localzet.com/projects/engine/requirements), [installation](https://server.localzet.com/projects/engine/install), [architecture](https://server.localzet.com/projects/engine/architecture), [compatibility with Engine 8](https://server.localzet.com/projects/engine/compatibility), and [test limits](https://server.localzet.com/projects/engine/testing). [Release notes](https://github.com/Triangle-org/Engine/releases/tag/v9.0.0). - [Triangle Engine HTTP](https://server.localzet.com/projects/engine-http): release 3.0.0 for Engine 9, Router 2, Middleware 2, Server 7.1+, PHP 8.1+, and ext-curl. Its install guide contains a runnable HTTP listener and curl check. CORS is disabled by default. [Compatibility](https://server.localzet.com/projects/engine-http/compatibility), [security](https://server.localzet.com/projects/engine-http/security), and [tests](https://server.localzet.com/projects/engine-http/testing). [Release notes](https://github.com/Triangle-org/Engine-HTTP/releases/tag/v3.0.0). @@ -74,3 +74,14 @@ The current stable tags are Localzet Server 7.2.1, Triangle Engine 9.0.0, Router - [Engine HTTP installation](https://server.localzet.com/projects/engine-http/install), [request handling](https://server.localzet.com/projects/engine-http/requests), [security](https://server.localzet.com/projects/engine-http/security), and [test limits](https://server.localzet.com/projects/engine-http/testing). - [Engine WS installation](https://server.localzet.com/projects/engine-ws/install), [handshake and messages](https://server.localzet.com/projects/engine-ws/messages), [security](https://server.localzet.com/projects/engine-ws/security), and [test limits](https://server.localzet.com/projects/engine-ws/testing). - [Compatibility and migration](https://server.localzet.com/projects/engine/compatibility): Engine 8.1.11 targets Server 4; Engine 9.0.0 targets Server 7.1. The comparison documents changed Composer constraints, global helpers, and Fiber context behavior. +- [Triangle Console](https://server.localzet.com/projects/triangle-console): release 2.0.0, a Triangle Engine 9 application command layer; PHP 8.4.1+, Localzet Console 2.2+, Symfony Console/Process 8.1+. It is separate from Localzet Console. [English guide](https://server.localzet.com/projects/triangle-console/en). +- [Triangle Database](https://server.localzet.com/projects/triangle-database): release 2.0.0, Illuminate database/Eloquent integration for Engine 9; PHP 8.2+, Illuminate 12, Server 7. [English guide](https://server.localzet.com/projects/triangle-database/en). +- [Triangle Session](https://server.localzet.com/projects/triangle-session): release 2.0.0, Engine 9 session handlers; PHP 8.1+, Server 7.1+. PHP objects from serialized storage are not instantiated by default. [English guide](https://server.localzet.com/projects/triangle-session/en). +- [Triangle Events](https://server.localzet.com/projects/triangle-events): release 2.0.1, synchronous in-process dispatch for exact and prefix event names; it is not a durable or cross-worker queue. The patch fixes logger initialization when a listener throws and tests that exceptions are returned by `Events::emit()`. [English guide](https://server.localzet.com/projects/triangle-events/en), [release notes](https://github.com/Triangle-org/Events/releases/tag/v2.0.1). +- [Triangle View](https://server.localzet.com/projects/triangle-view): release 2.1.0, PHP `.phtml` rendering by default with optional template adapters; supports Engine 8 and 9. Raw templates do not auto-escape output. [English guide](https://server.localzet.com/projects/triangle-view/en). +- [Triangle Router](https://server.localzet.com/projects/triangle-router): release 2.0.7, HTTP route matching and dispatch for Engine 8 and 9. Route matching does not authorize requests or replace application HTTP semantics. [English guide](https://server.localzet.com/projects/triangle-router/en). +- [Triangle Middleware](https://server.localzet.com/projects/triangle-middleware): release 2.0.3, middleware contracts and configuration for Engine 8 and 9; the package does not itself run an HTTP server. [English guide](https://server.localzet.com/projects/triangle-middleware/en). +- [Triangle Cron](https://server.localzet.com/projects/triangle-cron): published release 1.0.3 targets Engine 8.1; Engine 9 source is not tagged or published. Do not request the preview `^2.0` constraint from Packagist. [English guide](https://server.localzet.com/projects/triangle-cron/en). +- [Triangle OAuth](https://server.localzet.com/projects/triangle-oauth): published release 3.0.9 requires PHP 8.2+ and Localzet HTTP 2; the current checkout adds an Engine dependency beyond the published tag. [English guide](https://server.localzet.com/projects/triangle-oauth/en). +- [Triangle Web](https://server.localzet.com/projects/triangle-web): release 8.0.1 project template for Engine 8.1, HTTP adapter 2, PHP 8.2+. Its published template is not an Engine 9 starter. [English guide](https://server.localzet.com/projects/triangle-web/en). +- [Triangle WS](https://server.localzet.com/projects/triangle-ws): published release 1.0.4 targets Engine 8.1 and Engine WS 2; current checkout uses Engine WS 1.1. Default runtime is one worker and local sends do not cross processes. [English guide](https://server.localzet.com/projects/triangle-ws/en). diff --git a/public/sitemap.xml b/public/sitemap.xml index c69d671..ddaaceb 100644 --- a/public/sitemap.xml +++ b/public/sitemap.xml @@ -573,6 +573,556 @@ weekly 0.7
+ + https://server.localzet.com/projects/triangle-console + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-console/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-console/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-console/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-console/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-console/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-console/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-console/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-console/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-console/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-cron/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-database/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-events/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-middleware/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-oauth/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-router/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-session/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-view/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-web/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws/en + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws/en/compatibility + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws/en/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws/en/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws/en/usage + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws/install + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws/operations + weekly + 0.7 + + + https://server.localzet.com/projects/triangle-ws/usage + weekly + 0.7 + https://server.localzet.com/projects/tunnel weekly diff --git a/src/components/Header.jsx b/src/components/Header.jsx index e028c0a..4bd7042 100644 --- a/src/components/Header.jsx +++ b/src/components/Header.jsx @@ -8,24 +8,47 @@ import {ModeToggle} from '@/components/ModeToggle' import {MobileSearch, Search} from '@/components/Search' import {useRouter} from 'next/router' -const projects = [ - {id: 'server', title: 'Server', href: '/'}, - {id: 'cluster', title: 'Cluster', href: '/projects/cluster'}, - {id: 'engine', title: 'Triangle Engine', href: '/projects/engine'}, - {id: 'engine-http', title: 'Engine HTTP', href: '/projects/engine-http'}, - {id: 'engine-ws', title: 'Engine WS', href: '/projects/engine-ws'}, - {id: 'cron', title: 'Cron', href: '/projects/cron'}, - {id: 'httpclient', title: 'HTTP Client', href: '/projects/httpclient'}, - {id: 'mqtt', title: 'MQTT', href: '/projects/mqtt'}, - {id: 'psr7', title: 'PSR-7', href: '/projects/psr7'}, - {id: 'proxy', title: 'Proxy', href: '/projects/proxy'}, - {id: 'socks5', title: 'SOCKS5', href: '/projects/socks5'}, - {id: 'socketio', title: 'Socket.IO', href: '/projects/socketio'}, - {id: 'storage', title: 'Storage', href: '/projects/storage'}, - {id: 'tunnel', title: 'Tunnel', href: '/projects/tunnel'}, - {id: 'noter', title: 'Noter', href: '/projects/noter'}, - {id: 'media', title: 'Media', href: '/projects/media'}, +const projectGroups = [ + { + title: 'Localzet', + projects: [ + {id: 'server', title: 'Server', href: '/'}, + {id: 'cluster', title: 'Cluster', href: '/projects/cluster'}, + {id: 'console', title: 'Localzet Console', href: '/projects/console'}, + {id: 'cron', title: 'Cron', href: '/projects/cron'}, + {id: 'httpclient', title: 'HTTP Client', href: '/projects/httpclient'}, + {id: 'mqtt', title: 'MQTT', href: '/projects/mqtt'}, + {id: 'psr7', title: 'PSR-7', href: '/projects/psr7'}, + {id: 'proxy', title: 'Proxy', href: '/projects/proxy'}, + {id: 'socks5', title: 'SOCKS5', href: '/projects/socks5'}, + {id: 'socketio', title: 'Socket.IO', href: '/projects/socketio'}, + {id: 'storage', title: 'Storage', href: '/projects/storage'}, + {id: 'tunnel', title: 'Tunnel', href: '/projects/tunnel'}, + {id: 'noter', title: 'Noter', href: '/projects/noter'}, + ], + }, + { + title: 'Triangle', + projects: [ + {id: 'engine', title: 'Engine', href: '/projects/engine'}, + {id: 'engine-http', title: 'Engine HTTP', href: '/projects/engine-http'}, + {id: 'engine-ws', title: 'Engine WS', href: '/projects/engine-ws'}, + {id: 'triangle-console', title: 'Console', href: '/projects/triangle-console'}, + {id: 'triangle-cron', title: 'Cron', href: '/projects/triangle-cron'}, + {id: 'triangle-database', title: 'Database', href: '/projects/triangle-database'}, + {id: 'triangle-events', title: 'Events', href: '/projects/triangle-events'}, + {id: 'triangle-middleware', title: 'Middleware', href: '/projects/triangle-middleware'}, + {id: 'triangle-oauth', title: 'OAuth', href: '/projects/triangle-oauth'}, + {id: 'triangle-router', title: 'Router', href: '/projects/triangle-router'}, + {id: 'triangle-session', title: 'Session', href: '/projects/triangle-session'}, + {id: 'triangle-view', title: 'View', href: '/projects/triangle-view'}, + {id: 'triangle-web', title: 'Web', href: '/projects/triangle-web'}, + {id: 'triangle-ws', title: 'WS', href: '/projects/triangle-ws'}, + {id: 'media', title: 'Media', href: '/projects/media'}, + ], + }, ] +const projects = projectGroups.flatMap((group) => group.projects) export const Header = forwardRef(function Header({className}, ref) { let router = useRouter() @@ -77,7 +100,13 @@ export const Header = forwardRef(function Header({className}, ref) { value={currentProject} onChange={(event) => router.push(projects.find((project) => project.id === event.target.value)?.href ?? '/')} > - {projects.map((project) => )} + {projectGroups.map((group) => ( + + {group.projects.map((project) => ( + + ))} + + ))}
diff --git a/src/components/Navigation.jsx b/src/components/Navigation.jsx index 65c8319..6c0d2b8 100644 --- a/src/components/Navigation.jsx +++ b/src/components/Navigation.jsx @@ -289,7 +289,63 @@ const projectNavigation = { {title: 'Tests and coverage limits', href: '/projects/engine/en/testing'}, ]}, ], - console: [{title: 'Console', links: [{title: 'Обзор', href: '/projects/console'}, {title: 'Установка и команды', href: '/projects/console/start'}, {title: 'Laravel bridge и TUI', href: '/projects/console/reference'}]}], + console: [{title: 'Localzet Console', links: [{title: 'Обзор', href: '/projects/console'}, {title: 'Установка и команды', href: '/projects/console/start'}, {title: 'Laravel bridge и TUI', href: '/projects/console/reference'}]}], + 'triangle-console': [{title: 'Triangle Console', links: [{title: 'Обзор и установка', href: '/projects/triangle-console'}, {title: 'Overview and installation', href: '/projects/triangle-console/en'}]}], + 'triangle-database': [{title: 'Triangle Database', links: [{title: 'Обзор и установка', href: '/projects/triangle-database'}, {title: 'Overview and installation', href: '/projects/triangle-database/en'}]}], + 'triangle-session': [{title: 'Triangle Session', links: [{title: 'Обзор и установка', href: '/projects/triangle-session'}, {title: 'Overview and installation', href: '/projects/triangle-session/en'}]}], + 'triangle-cron': [{title: 'Triangle Cron', links: [{title: 'Обзор и статус релиза', href: '/projects/triangle-cron'}, {title: 'Overview and release status', href: '/projects/triangle-cron/en'}]}], + 'triangle-middleware': [{title: 'Triangle Middleware', links: [{title: 'Обзор и установка', href: '/projects/triangle-middleware'}, {title: 'Overview and installation', href: '/projects/triangle-middleware/en'}]}], + 'triangle-events': [ + {title: 'Triangle Events · Русский', links: [ + {title: 'Обзор и быстрый путь', href: '/projects/triangle-events'}, + {title: 'Установка', href: '/projects/triangle-events/install'}, + {title: 'Обработчики и вызов', href: '/projects/triangle-events/usage'}, + {title: 'Эксплуатация и ограничения', href: '/projects/triangle-events/operations'}, + {title: 'Совместимость и проверки', href: '/projects/triangle-events/compatibility'}, + ]}, + {title: 'Triangle Events · English', links: [ + {title: 'Overview and quick start', href: '/projects/triangle-events/en'}, + {title: 'Installation', href: '/projects/triangle-events/en/install'}, + {title: 'Listeners and dispatch', href: '/projects/triangle-events/en/usage'}, + {title: 'Operations and limits', href: '/projects/triangle-events/en/operations'}, + {title: 'Compatibility and checks', href: '/projects/triangle-events/en/compatibility'}, + ]}, + ], + 'triangle-view': [ + {title: 'Triangle View · Русский', links: [ + {title: 'Обзор', href: '/projects/triangle-view'}, + {title: 'Установка', href: '/projects/triangle-view/install'}, + {title: 'Рендеринг', href: '/projects/triangle-view/usage'}, + {title: 'Настройка и безопасность', href: '/projects/triangle-view/operations'}, + {title: 'Совместимость и тесты', href: '/projects/triangle-view/compatibility'}, + ]}, + {title: 'Triangle View · English', links: [ + {title: 'Overview', href: '/projects/triangle-view/en'}, + {title: 'Installation', href: '/projects/triangle-view/en/install'}, + {title: 'Rendering', href: '/projects/triangle-view/en/usage'}, + {title: 'Configuration and security', href: '/projects/triangle-view/en/operations'}, + {title: 'Compatibility and tests', href: '/projects/triangle-view/en/compatibility'}, + ]}, + ], + 'triangle-router': [ + {title: 'Triangle Router · Русский', links: [ + {title: 'Обзор', href: '/projects/triangle-router'}, + {title: 'Установка', href: '/projects/triangle-router/install'}, + {title: 'Маршруты и dispatch', href: '/projects/triangle-router/usage'}, + {title: 'Интеграция Engine', href: '/projects/triangle-router/operations'}, + {title: 'Совместимость и безопасность', href: '/projects/triangle-router/compatibility'}, + ]}, + {title: 'Triangle Router · English', links: [ + {title: 'Overview', href: '/projects/triangle-router/en'}, + {title: 'Installation', href: '/projects/triangle-router/en/install'}, + {title: 'Routes and dispatch', href: '/projects/triangle-router/en/usage'}, + {title: 'Engine integration', href: '/projects/triangle-router/en/operations'}, + {title: 'Compatibility and security', href: '/projects/triangle-router/en/compatibility'}, + ]}, + ], + 'triangle-oauth': [{title: 'Triangle OAuth', links: [{title: 'Обзор и опубликованный статус', href: '/projects/triangle-oauth'}, {title: 'Overview and published status', href: '/projects/triangle-oauth/en'}]}], + 'triangle-web': [{title: 'Triangle Web', links: [{title: 'Обзор и запуск шаблона', href: '/projects/triangle-web'}, {title: 'Overview and getting started', href: '/projects/triangle-web/en'}]}], + 'triangle-ws': [{title: 'Triangle WS', links: [{title: 'Обзор и ограничения', href: '/projects/triangle-ws'}, {title: 'Overview and limits', href: '/projects/triangle-ws/en'}]}], cron: [{title: 'Cron', links: [{title: 'Обзор', href: '/projects/cron'}, {title: 'Установка и расписания', href: '/projects/cron/start'}, {title: 'API и эксплуатация', href: '/projects/cron/reference'}]}], httpclient: [{title: 'HTTP Client', links: [{title: 'Обзор', href: '/projects/httpclient'}, {title: 'Первый запрос', href: '/projects/httpclient/start'}, {title: 'Запросы и обработка ответов', href: '/projects/httpclient/reference'}]}], mqtt: [{title: 'MQTT', links: [{title: 'Обзор и статус', href: '/projects/mqtt'}, {title: 'Подключение и обмен сообщениями', href: '/projects/mqtt/start'}, {title: 'Параметры и надёжность', href: '/projects/mqtt/reference'}]}], diff --git a/src/pages/_app.jsx b/src/pages/_app.jsx index 7064987..ad49b44 100644 --- a/src/pages/_app.jsx +++ b/src/pages/_app.jsx @@ -12,9 +12,23 @@ import 'focus-visible' const SITE_URL = 'https://server.localzet.com' const DEFAULT_TITLE = 'Localzet Server 7.2.1 — документация' -const DEFAULT_DESCRIPTION = 'Официальная документация Localzet Server: асинхронный PHP runtime для HTTP/1.x, WebSocket, TCP и UDP, с event loop и управлением worker-процессами.' +const DEFAULT_DESCRIPTION = 'Техническая документация Localzet Server и связанных PHP-проектов Localzet и Triangle: установка, архитектура, примеры, безопасность и совместимость.' const CLUSTER_TITLE = 'Localzet Cluster — документация' const CLUSTER_DESCRIPTION = 'Документация Localzet Cluster: распределённая архитектура Gateway/Business Worker для приложений на PHP, регистрация узлов и маршрутизация клиентских соединений.' +const BILINGUAL_PROJECTS = new Set([ + 'media', + 'triangle-console', + 'triangle-cron', + 'triangle-database', + 'triangle-events', + 'triangle-middleware', + 'triangle-oauth', + 'triangle-router', + 'triangle-session', + 'triangle-view', + 'triangle-web', + 'triangle-ws', +]) function onRouteChange() { useMobileNavigationStore.getState().close() @@ -37,8 +51,12 @@ function isClusterDocumentation(pathname) { return pathname.startsWith('/projects/cluster') } -function getMediaLocalePaths(pathname) { - const russianRoot = '/projects/media' +function getProjectLocalePaths(pathname, projectId) { + if (!BILINGUAL_PROJECTS.has(projectId)) { + return null + } + + const russianRoot = `/projects/${projectId}` const englishRoot = `${russianRoot}/en` if (pathname === russianRoot || pathname === englishRoot) { @@ -57,6 +75,94 @@ function getMediaLocalePaths(pathname) { } const RELATED_PROJECTS = { + console: [ + 'Localzet Console', + 'PHP command-line application library based on Symfony Console, with an opt-in Laravel command bridge and Unicode-safe terminal interfaces.', + 'https://github.com/localzet/Console', + 'Stable release 2.2.1 requires PHP 8.4.1+.', + [ + 'Build CLI applications with Symfony Console APIs', + 'Register Laravel commands explicitly with an existing application container', + 'Render Unicode-aware ANSI tables and bounded terminal dashboards', + ], + ], + 'triangle-console': [ + 'Triangle Console', + 'Console application integration for Triangle Engine with command discovery, application generators, and an explicit Laravel command bridge.', + 'https://github.com/Triangle-org/Console', + 'Stable release 2.0.0 targets PHP 8.4.1+ and Triangle Engine 9.', + ['Discover Triangle application commands', 'Register framework and plugin commands', 'Bridge existing Illuminate commands when needed'], + ], + 'triangle-database': [ + 'Triangle Database', + 'Database integration for Triangle Engine applications, including connections, query builder, Eloquent models, events, and pagination.', + 'https://github.com/Triangle-org/Database', + 'Stable release 2.0.0 targets PHP 8.2+ and Triangle Engine 9.', + ['Configure database connections and drivers', 'Use query builder and Eloquent integration', 'Handle process-local connection lifecycle'], + ], + 'triangle-session': [ + 'Triangle Session', + 'Session handlers for Triangle Engine applications, with file storage by default and optional Redis, cluster, and MongoDB backends.', + 'https://github.com/Triangle-org/Session', + 'Stable release 2.0.0 targets Triangle Engine 9 and Localzet Server 7.1+.', + ['Configure session cookies and handlers', 'Share session storage across workers with a shared backend', 'Keep PHP object deserialization disabled by default'], + ], + 'triangle-events': [ + 'Triangle Events', + 'In-process event dispatch for Triangle Engine applications with exact and prefix listeners.', + 'https://github.com/Triangle-org/Events', + 'Stable release 2.0.1 targets PHP 8.1+ and Triangle Engine 9.', + ['Register and remove event listeners', 'Dispatch events synchronously in the current process', 'Use prefix listeners for event families'], + ], + 'triangle-view': [ + 'Triangle View', + 'Template rendering integration for Triangle Engine applications, with PHP templates by default and optional template adapters.', + 'https://github.com/Triangle-org/View', + 'Stable release 2.1.0 supports Triangle Engine 8 and 9.', + ['Render PHP templates with `.phtml` files', 'Pass request-scoped and explicit template variables', 'Add optional Blade, Twig, or Think adapters'], + ], + 'triangle-router': [ + 'Triangle Router', + 'HTTP routing for Triangle Engine with method, named, optional, grouped, resource, and middleware routes.', + 'https://github.com/Triangle-org/Router', + 'Stable release 2.0.7 supports Triangle Engine 8 and 9.', + ['Define method and named routes', 'Compose groups, child routers, and resources', 'Apply route middleware and route caching'], + ], + 'triangle-middleware': [ + 'Triangle Middleware', + 'Middleware pipeline for Triangle Engine applications, with route integration and explicit execution order.', + 'https://github.com/Triangle-org/Middleware', + 'Stable release 2.0.3 targets Triangle Engine 9.', + ['Register request and response middleware', 'Control middleware order and scope', 'Integrate middleware with routed requests'], + ], + 'triangle-cron': [ + 'Triangle Cron', + 'Scheduled job integration for Triangle applications. The published package remains on Engine 8; Engine 9 work is an untagged preview.', + 'https://github.com/Triangle-org/Cron', + 'Published release 1.0.3 targets Triangle Engine 8; Engine 9 preview is not released.', + ['Review the published Engine 8 package contract', 'Distinguish tagged releases from preview source', 'Check current package constraints before migration'], + ], + 'triangle-oauth': [ + 'Triangle OAuth', + 'OAuth 1, OAuth 2, and OpenID provider integrations with callback handling and state storage for Triangle applications.', + 'https://github.com/Triangle-org/OAuth', + 'Published release 3.0.9 requires PHP 8.2+ and Localzet HTTP 2; current checkout has additional Engine requirements.', + ['Configure OAuth and OpenID providers', 'Handle callback and state storage', 'Verify published and current-source dependency constraints'], + ], + 'triangle-web': [ + 'Triangle Web', + 'MVC application template for Triangle Engine, with HTTP routing, controllers, configuration, and project structure.', + 'https://github.com/Triangle-org/Web', + 'Published release 8.0.1 targets PHP 8.2+ and Triangle Engine 8.1.', + ['Create an application from the project template', 'Configure server, routes, controllers, and views', 'Inspect the exact dependency lock before migrating to Engine 9'], + ], + 'triangle-ws': [ + 'Triangle WS', + 'WebSocket-first application template for Triangle Engine, with path-scoped local sends and a single-worker default.', + 'https://github.com/Triangle-org/WS', + 'Published release 1.0.4 targets Triangle Engine 8.1 and Engine WS 2; current checkout uses Engine WS 1.1.', + ['Create a WebSocket application from the template', 'Register route callbacks and exchange payloads', 'Account for single-process state and version differences'], + ], engine: [ 'Triangle Engine', 'PHP application engine for Triangle with request handling, routing integration, service lifecycle, and runtime helpers.', @@ -126,7 +232,10 @@ export default function App({Component, pageProps}) { const description = pageProps.description ?? (cluster ? CLUSTER_DESCRIPTION : relatedProject?.[1] ?? DEFAULT_DESCRIPTION) const canonicalPath = router.asPath.split(/[?#]/, 1)[0] const currentUrl = `${cluster ? 'https://server.localzet.com' : SITE_URL}${canonicalPath}` - const mediaLocalePaths = projectId === 'media' ? getMediaLocalePaths(router.pathname) : null + const projectLocalePaths = projectId ? getProjectLocalePaths(router.pathname, projectId) : null + const softwareId = `${SITE_URL}/#software-${cluster ? 'cluster' : projectId ?? 'server'}` + const semanticVersion = relatedProject?.[3]?.match(/\b\d+\.\d+\.\d+\b/)?.[0] + const phpVersion = relatedProject?.[3]?.match(/PHP\s+(\d+(?:\.\d+){1,2})/i)?.[1] const robots = current ? 'index,follow' : 'noindex,follow' const graph = { '@context': 'https://schema.org', @@ -134,9 +243,9 @@ export default function App({Component, pageProps}) { { '@type': 'WebSite', '@id': `${SITE_URL}/#website`, - name: cluster ? CLUSTER_TITLE : relatedProject?.[0] ?? 'Localzet Server — документация', + name: 'Localzet Server documentation', url: SITE_URL, - description, + description: DEFAULT_DESCRIPTION, inLanguage: language, publisher: {'@id': `${SITE_URL}/#publisher`}, }, @@ -148,15 +257,13 @@ export default function App({Component, pageProps}) { }, { '@type': 'SoftwareSourceCode', - '@id': `${SITE_URL}/#software`, + '@id': softwareId, name: cluster ? 'Localzet Cluster' : relatedProject?.[0] ?? 'Localzet Server', description, codeRepository: cluster ? 'https://github.com/localzet/Cluster' : relatedProject?.[2] ?? 'https://github.com/localzet/Server', programmingLanguage: 'PHP', - runtimePlatform: 'PHP 8.1 or newer', - version: cluster - ? 'current Cluster source, requires Server ^7.0' - : relatedProject?.[3] ?? (relatedProject ? 'current repository source' : '7.2.1'), + runtimePlatform: phpVersion ? `PHP ${phpVersion} or newer` : 'PHP 8.1 or newer', + version: cluster ? 'current source' : semanticVersion ?? (relatedProject ? 'current source' : '7.2.1'), license: 'https://spdx.org/licenses/AGPL-3.0-or-later.html', author: { '@type': 'Person', @@ -184,7 +291,7 @@ export default function App({Component, pageProps}) { url: currentUrl, inLanguage: language, isPartOf: {'@id': `${SITE_URL}/#website`}, - about: {'@id': `${SITE_URL}/#software`}, + about: {'@id': softwareId}, ...(router.pathname !== '/' && { breadcrumb: {'@id': `${currentUrl}#breadcrumb`}, }), @@ -219,10 +326,10 @@ export default function App({Component, pageProps}) { {router.pathname === '/' ? DEFAULT_TITLE : `${title} — ${cluster ? 'Localzet Cluster' : relatedProject?.[0] ?? 'Localzet Server'}`} - {mediaLocalePaths && <> - - - + {projectLocalePaths && <> + + + } diff --git a/src/pages/projects/mqtt.mdx b/src/pages/projects/mqtt.mdx index c82b815..ab46135 100644 --- a/src/pages/projects/mqtt.mdx +++ b/src/pages/projects/mqtt.mdx @@ -6,7 +6,7 @@ export const description = 'MQTT 3.1.1 и MQTT 5 клиент для Localzet Se # Localzet MQTT [Начало работы](/projects/mqtt/start) · [API и эксплуатация](/projects/mqtt/reference) -MQTT [`1.0.1`](https://github.com/localzet/MQTT/releases/tag/v1.0.1) — клиент MQTT 3.1.1 и MQTT 5 для Localzet Server 7. В этом выпуске восстановлены legacy-алиасы протокольных классов для Server 7. +MQTT [`1.0.2`](https://github.com/localzet/MQTT/releases/tag/v1.0.2) — клиент MQTT 3.1.1 и MQTT 5 для Localzet Server 7. В этом выпуске credentials, темы, properties и тела сообщений исключены из debug-логов; сетевое поведение и доставка не изменены. ```sh composer config repositories.localzet-mqtt vcs https://github.com/localzet/MQTT diff --git a/src/pages/projects/storage.mdx b/src/pages/projects/storage.mdx index 6b70358..14322aa 100644 --- a/src/pages/projects/storage.mdx +++ b/src/pages/projects/storage.mdx @@ -4,17 +4,18 @@ export const description = 'Общее in-memory хранилище Localzet Ser # Localzet Storage [Начало работы](/projects/storage/start) · [API и эксплуатация](/projects/storage/reference) -Storage `1.0.2` — общее in-memory хранилище для процессов приложения на Localzet Server 7 с безопасным framing и отключённой по умолчанию десериализацией объектов. +Storage `2.0.0` — общее in-memory хранилище для процессов приложения на Localzet Server 7 с ограниченным framing и запретом объектов и циклических массивов по умолчанию. ```sh -composer require localzet/storage:^1.0 +composer config repositories.localzet-storage vcs https://github.com/localzet/Storage +composer require localzet/storage:^2.0 ``` -Текущий стабильный выпуск — [`1.0.2`](https://github.com/localzet/Storage/releases/tag/v1.0.2). В нём исправлено чтение полного заголовка и payload-а, а запись корректно обрабатывает частичный результат `fwrite()`. +Текущий стабильный выпуск — [`2.0.0`](https://github.com/localzet/Storage/releases/tag/v2.0.0). Он обновляет framing для Server 7, корректно обрабатывает частичные чтения и записи, ограничивает размер фрейма 64 МиБ и по умолчанию принимает только скаляры и ациклические массивы. Репозиторий пока не публикует пакет на Packagist, поэтому Composer подключается напрямую к VCS. Storage предоставляет клиент-серверное общее in-memory хранилище. Пакет требует PHP 8.2+ и Localzet Server 7. По умолчанию listener привязан к `127.0.0.1:8008`; встроенной аутентификации нет. -Сетевой формат совместим с PHP serialization, но десериализация объектов выключена. Opt-in `allowObjectSerialization: true` на обеих сторонах допустим только в доверенной изолированной сети. Значения хранятся в памяти процесса и не обеспечивают персистентность или репликацию. +Переход с версии 1.x требует согласованно обновить клиент и сервер; удалите объекты и циклические массивы из передаваемых значений либо включайте `allowObjectSerialization: true` на обеих сторонах только в доверенной изолированной сети. Значения хранятся в памяти процесса и не обеспечивают персистентность или репликацию. Перед внешней сетевой привязкой настройте ACL; проверяйте размеры фреймов, доступность сервиса и операции конкурентных клиентов. diff --git a/src/pages/projects/storage/reference.mdx b/src/pages/projects/storage/reference.mdx index 54fe458..6f487f9 100644 --- a/src/pages/projects/storage/reference.mdx +++ b/src/pages/projects/storage/reference.mdx @@ -3,7 +3,7 @@ export const description = 'Клиентский API, hash-based sharding, PHP s # Storage: API и эксплуатация -Нужны PHP 8.2+ и Localzet Server `^7.0`. `new localzet\Storage\Server($ip = '127.0.0.1', $port = 8008, $allowObjectSerialization = false)` создаёт frame listener с одним worker. `new Client($servers, $allowObjectSerialization = false)` принимает один `host:port` или массив адресов. +Нужны PHP 8.2+ и Localzet Server `^7.0`. `new localzet\Storage\Server($ip = '127.0.0.1', $port = 8008, $allowObjectSerialization = false)` создаёт frame listener с одним worker. `new Client($servers, $allowObjectSerialization = false)` принимает один `host:port` или массив адресов. Текущий выпуск — [`2.0.0`](https://github.com/localzet/Storage/releases/tag/v2.0.0); для установки добавьте VCS-источник, как показано в [начале работы](/projects/storage/start). ## Операции и размещение @@ -20,7 +20,7 @@ export const description = 'Клиентский API, hash-based sharding, PHP s ## Wire format и границы безопасности -Протокол использует длино-префиксированные PHP serialized frames без аутентификации и шифрования. Значения в сети должны быть совместимы с PHP serialization. Десериализация объектов выключена по умолчанию на клиенте и сервере; включение `allowObjectSerialization: true` с обеих сторон разрешено только для доверенной изолированной сети, где каждый peer контролируется тем же владельцем. +Протокол использует длино-префиксированные PHP serialized frames с максимумом 64 МиБ на фрейм, без аутентификации и шифрования. Значения в сети должны быть совместимы с PHP serialization. Десериализация объектов выключена по умолчанию на клиенте и сервере; объекты и циклические массивы отклоняются. Включение `allowObjectSerialization: true` с обеих сторон разрешено только для доверенной изолированной сети, где каждый peer контролируется тем же владельцем. Оставляйте listener на loopback или закрывайте его ACL/firewall. Не выставляйте порт 8008 в Интернет и не отправляйте неограниченные payload: протокол не предоставляет клиентской авторизации, TTL API, лимита памяти или долговременного хранения. Все данные в RAM одного процесса; они пропадают при остановке. Масштабирование узлами — шардирование, а не репликация. diff --git a/src/pages/projects/storage/start.mdx b/src/pages/projects/storage/start.mdx index c028063..f84a8cb 100644 --- a/src/pages/projects/storage/start.mdx +++ b/src/pages/projects/storage/start.mdx @@ -3,11 +3,11 @@ export const description = 'Запуск Localzet Storage на loopback и ра # Storage: начало работы -Storage — простое общее in-memory хранилище для процессов приложения. Установите пакет вместе с Localzet Server 7: +Storage 2.0.0 — общее in-memory хранилище для приложений на Localzet Server 7. Пакет доступен через VCS-репозиторий, поскольку ещё не опубликован на Packagist: ```sh composer config repositories.localzet-storage vcs https://github.com/localzet/Storage -composer require localzet/storage:^1.0 +composer require localzet/storage:^2.0 ``` Создайте серверное приложение. Storage слушает loopback и использует один worker по умолчанию: @@ -39,4 +39,4 @@ $cache->increment('counter'); `set`, `get`, `add`, `cas`, `increment` и `delete` работают через клиентский API; прочитайте возвращаемое значение, чтобы обработать отсутствующий ключ или неудачную условную запись. Клиент распределяет ключи между заданными адресами по CRC32, поэтому изменение списка узлов перемещает часть ключей. -Данные теряются при остановке процесса; TTL, персистентности, репликации, аутентификации и шифрования нет. Не открывайте порт наружу. Объектная десериализация выключена; см. [безопасность и wire format](/projects/storage/reference). +Данные теряются при остановке процесса; TTL, персистентности, репликации, аутентификации и шифрования нет. Не открывайте порт наружу. Версия 2 несовместима с клиентами, которые отправляют объекты или циклические массивы без явного opt-in. См. [безопасность и wire format](/projects/storage/reference). diff --git a/src/pages/projects/triangle-console.mdx b/src/pages/projects/triangle-console.mdx new file mode 100644 index 0000000..a343283 --- /dev/null +++ b/src/pages/projects/triangle-console.mdx @@ -0,0 +1,52 @@ +export const pageTitle = 'Triangle Console' +export const description = 'CLI-интеграция Triangle Engine с командами Symfony Console и Illuminate.' + +# Triangle Console + +Triangle Console связывает Triangle Engine с командами Symfony Console и Illuminate. Это компонент Triangle Framework, отдельный от базовой библиотеки Localzet Console. Текущий выпуск — [2.0.0](https://github.com/Triangle-org/Console/releases/tag/v2.0.0). + +Требования: PHP `^8.4.1`, Engine `^9.0`, Localzet Console `^2.2`, Symfony Console/Process `^8.1`. + +```sh +composer require triangle/console:^2.0 +composer show triangle/console +``` + +## Первая команда + +Создайте класс под PSR-4 namespace приложения в `app/command`: + +```php +writeln('Report is ready.'); + return self::SUCCESS; + } +} +``` + +После Composer autoload и bootstrap/configuration Engine создайте `new Triangle\Console\Console()` и вызовите `run()`. Engine config должен быть загружен для автопоиска команд из `app/command`, `config/command.php` и включённых плагинов. Классы из config обязаны задавать Symfony-совместимый `defaultName`. + +Illuminate-команды добавляются явно: `(new Triangle\Console\Console([], false))->useIlluminate($container)` затем `addIlluminateCommand($command)`. Аргумент `false` отключает автоматические package commands для ручной композиции. + +## Конфигурация, сборка и безопасность + +`Triangle\Console\Install::install()` копирует отсутствующие шаблоны конфигурации, не перезаписывая существующие. Встроенные команды включают `make:command`, `make:controller`, `make:model`, `app:create`, `plugin:create`, `build:phar`, `build:bin`. Параметры `config/console.php` задают каталоги, исключения, имена артефактов и целевую версию PHP; шаблон бинарной сборки указывает PHP 8.4 и memory limit 256M. Проверьте состав артефакта; упаковка не гарантирует невозможность извлечь исходный код. Приватные ключи PHAR храните вне репозитория; не включайте секреты в исходники и артефакты. + +## Совместимость и проверки + +Тег `v2.0.0` несовместим с Engine 8: обновите PHP до 8.4.1+ и Engine до 9, затем проверьте обнаружение команд и собственные build workflows. В пакете доступны `composer validate --strict --no-check-publish` и `composer run check`; последний запускает lint и `tests/run.php`, который проверяет Symfony command registration и Illuminate bridge. Он не собирает production PHAR/binary и не проверяет целевую ОС. + +## Практические руководства + +[Установка](/projects/triangle-console/install) · [Использование](/projects/triangle-console/usage) · [Эксплуатация](/projects/triangle-console/operations) · [Совместимость и тесты](/projects/triangle-console/compatibility). diff --git a/src/pages/projects/triangle-console/compatibility.mdx b/src/pages/projects/triangle-console/compatibility.mdx new file mode 100644 index 0000000..0e095dd --- /dev/null +++ b/src/pages/projects/triangle-console/compatibility.mdx @@ -0,0 +1,23 @@ +export const pageTitle = 'Совместимость, миграция и тесты' +export const description = 'Переход на Triangle Console 2 и границы проверок пакета.' + +# Совместимость, миграция и тесты + +Опубликованный тег `v2.0.0` требует PHP `^8.4.1`, Engine `^9.0`, Localzet Console `^2.2`, Symfony Console/Process `^8.1`. Engine 8 и более ранняя линия Triangle Console несовместимы с этим major выпуском. Проверяйте версию через `composer show triangle/console` и lock-файл приложения. + +## Миграция + +1. Обновите PHP до 8.4.1+ и Engine до 9. +2. Выполните `composer update triangle/console --with-all-dependencies` для согласованного пересчёта связанных пакетов. +3. Сверьте старый `config/console.php` с шаблоном 2.x; установщик не перезаписывает существующий конфиг. +4. Проверьте `defaultName`, PSR-4 автозагрузку, команды плагинов и собственные сценарии сборки. + +## Локальная проверка + +```sh +composer install +composer validate --strict --no-check-publish +composer run check +``` + +`check` выполняет PHP lint и `tests/run.php`; smoke test проверяет регистрацию Symfony-команды, наличие команды сборки и выполнение Illuminate-команды через bridge. Он не собирает реальный PHAR/binary, не тестирует target OS и не заменяет проверку проектных команд. diff --git a/src/pages/projects/triangle-console/en.mdx b/src/pages/projects/triangle-console/en.mdx new file mode 100644 index 0000000..3c689c6 --- /dev/null +++ b/src/pages/projects/triangle-console/en.mdx @@ -0,0 +1,52 @@ +export const pageTitle = 'Triangle Console' +export const description = 'CLI integration for Triangle Engine with Symfony Console and Illuminate commands.' + +# Triangle Console + +Triangle Console connects Triangle Engine to Symfony Console and Illuminate commands. It is a Triangle Framework component, distinct from the Localzet Console base library. Current release: [2.0.0](https://github.com/Triangle-org/Console/releases/tag/v2.0.0). + +Requirements: PHP `^8.4.1`, Engine `^9.0`, Localzet Console `^2.2`, Symfony Console/Process `^8.1`. + +```sh +composer require triangle/console:^2.0 +composer show triangle/console +``` + +## First command + +Create a PSR-4 mapped class under `app/command`: + +```php +writeln('Report is ready.'); + return self::SUCCESS; + } +} +``` + +After Composer autoload and Engine bootstrap/configuration, instantiate `Triangle\Console\Console` and call `run()`. Engine config must be loaded for discovery from `app/command`, `config/command.php`, and enabled plugins. Config-listed commands require Symfony-compatible `defaultName`. + +Add Illuminate commands explicitly: `(new Triangle\Console\Console([], false))->useIlluminate($container)`, then call `addIlluminateCommand($command)`. The `false` argument disables automatic package commands for manual composition. + +## Configuration, builds, and security + +`Triangle\Console\Install::install()` copies missing config templates without overwriting existing files. Built-in commands include `make:command`, `make:controller`, `make:model`, `app:create`, `plugin:create`, `build:phar`, and `build:bin`. `config/console.php` controls directories, exclusions, artifact names, and PHP target; the binary build template targets PHP 8.4 with a 256M memory limit. Inspect build contents; packaging does not make source extraction impossible. Keep PHAR signing keys outside the repository and do not include secrets in sources or artifacts. + +## Compatibility and checks + +Tag `v2.0.0` is incompatible with Engine 8. Upgrade PHP to 8.4.1+ and Engine to 9, then verify command discovery and custom build workflows. The package provides `composer validate --strict --no-check-publish` and `composer run check`; the latter runs lint and `tests/run.php`, which checks Symfony command registration and the Illuminate bridge. It does not create a production PHAR/binary or test a target OS. + +## Practical guides + +[Install](/projects/triangle-console/en/install) · [Usage](/projects/triangle-console/en/usage) · [Operations](/projects/triangle-console/en/operations) · [Compatibility and tests](/projects/triangle-console/en/compatibility). diff --git a/src/pages/projects/triangle-console/en/compatibility.mdx b/src/pages/projects/triangle-console/en/compatibility.mdx new file mode 100644 index 0000000..da81d47 --- /dev/null +++ b/src/pages/projects/triangle-console/en/compatibility.mdx @@ -0,0 +1,23 @@ +export const pageTitle = 'Compatibility, migration, and tests' +export const description = 'Upgrade to Triangle Console 2 and understand package check coverage.' + +# Compatibility, migration, and tests + +Published tag `v2.0.0` requires PHP `^8.4.1`, Engine `^9.0`, Localzet Console `^2.2`, and Symfony Console/Process `^8.1`. Engine 8 and earlier Triangle Console major lines are not compatible with this release. Check `composer show triangle/console` and the consuming project's lock file. + +## Migration + +1. Upgrade PHP to 8.4.1+ and Engine to 9. +2. Run `composer update triangle/console --with-all-dependencies` to resolve related packages together. +3. Compare old `config/console.php` with the 2.x template; installer does not overwrite existing config. +4. Verify command `defaultName`, PSR-4 loading, plugin commands, and custom build workflows. + +## Local checks + +```sh +composer install +composer validate --strict --no-check-publish +composer run check +``` + +`check` runs PHP lint and `tests/run.php`; the smoke test covers Symfony command registration, availability of a build command, and running an Illuminate command through the bridge. It does not create a real PHAR/binary, test target operating systems, or replace application-specific command checks. diff --git a/src/pages/projects/triangle-console/en/install.mdx b/src/pages/projects/triangle-console/en/install.mdx new file mode 100644 index 0000000..e919e58 --- /dev/null +++ b/src/pages/projects/triangle-console/en/install.mdx @@ -0,0 +1,19 @@ +export const pageTitle = 'Install Triangle Console' +export const description = 'Composer requirements and integration with Triangle Engine.' + +# Install Triangle Console + +Triangle Console 2.0.0 targets PHP `^8.4.1`, Triangle Engine `^9.0`, Localzet Console `^2.2`, Symfony Console and Process `^8.1`. + +```sh +composer require triangle/console:^2.0 +composer show triangle/console triangle/engine localzet/console symfony/console symfony/process +``` + +Use the project lock file as the deployment source of truth; `composer show` reports resolved versions. This package does not replace the base CLI library: it extends Localzet Console with Engine integration, application commands, and plugin discovery. + +## Bootstrap + +Load Composer autoloading and bootstrap/configure Triangle Engine before creating `Triangle\Console\Console`. With Engine loaded, Console reads `config/console.php` and `config/command.php`, discovers classes in `app/command`, and scans enabled plugins. A project entry point usually owns this bootstrap; do not create a second, inconsistent bootstrap. + +For manual configuration installation, call `Triangle\Console\Install::install()` in the Engine installer context. It copies missing templates and leaves existing application files unchanged. Compare the resulting `config/console.php` with the settings needed by your project. diff --git a/src/pages/projects/triangle-console/en/operations.mdx b/src/pages/projects/triangle-console/en/operations.mdx new file mode 100644 index 0000000..d1c48ca --- /dev/null +++ b/src/pages/projects/triangle-console/en/operations.mdx @@ -0,0 +1,14 @@ +export const pageTitle = 'Configuration and packaging' +export const description = 'Configure build commands and understand their operational limits.' + +# Configuration and packaging + +The `config/console.php` template contains `service.name` and a `build` section: input/output directories, exclusion pattern and file list, PHAR/binary filenames, stub, PHAR signature algorithm, and private-key path. `Triangle\Console\Install::install()` does not replace existing files, so compare and update old config manually. + +Built-in source commands include `make:command`, `make:controller`, `make:middleware`, `make:model`, `app:create`, `plugin:create`, `build:phar`, and `build:bin`. Check exact arguments with `list` and `help ` on the installed entry point. + +## Artifacts and secrets + +The default binary config targets PHP 8.4 and `memory_limit = 256M`. `ext-zip` is suggested for build bin; `ext-openssl` is suggested for OpenSSL PHAR signing. Verify required extensions before building. Ensure `.env`, credentials, and signing keys are absent from output: `.env` is excluded in the template, but inspect every artifact. Packaging does not make source extraction or analysis impossible. + +Keep keys outside the checkout with restricted access. Avoid secrets in CLI arguments because process lists or logs may expose them. Test the artifact on each target OS separately. diff --git a/src/pages/projects/triangle-console/en/usage.mdx b/src/pages/projects/triangle-console/en/usage.mdx new file mode 100644 index 0000000..21c811e --- /dev/null +++ b/src/pages/projects/triangle-console/en/usage.mdx @@ -0,0 +1,43 @@ +export const pageTitle = 'Commands and the Illuminate bridge' +export const description = 'Create Symfony commands, discover them, and explicitly add Illuminate commands.' + +# Commands and the Illuminate bridge + +Create a PSR-4 autoloadable command under `app/command`: + +```php +writeln('Report is ready.'); + return self::SUCCESS; + } +} +``` + +After Engine bootstrap, run `$console = new Triangle\Console\Console(); exit($console->run());`. CLI arguments go to the inherited `run()` method; invoke the application entry point with `list` or `app:report`. `config/command.php` is an array of class names, each requiring a Symfony-compatible `defaultName`. Enabled plugin command directories are discovered too. + +### Illuminate Console + +The bridge is explicit, for example when composing a console manually: + +```php +$console = (new Triangle\Console\Console([], false)) + ->useIlluminate(new Illuminate\Container\Container()); +$console->addIlluminateCommand(new App\Console\Commands\ReportCommand()); +$console->run(); +``` + +The second argument `false` disables automatic package command registration. Pass the container expected by your Illuminate commands. Regular commands continue to use the Symfony API. diff --git a/src/pages/projects/triangle-console/install.mdx b/src/pages/projects/triangle-console/install.mdx new file mode 100644 index 0000000..e155b99 --- /dev/null +++ b/src/pages/projects/triangle-console/install.mdx @@ -0,0 +1,19 @@ +export const pageTitle = 'Установка Triangle Console' +export const description = 'Требования Composer и подключение Triangle Console к Triangle Engine.' + +# Установка Triangle Console + +Triangle Console 2.0.0 рассчитан на PHP `^8.4.1`, Triangle Engine `^9.0`, Localzet Console `^2.2`, Symfony Console и Process `^8.1`. + +```sh +composer require triangle/console:^2.0 +composer show triangle/console triangle/engine localzet/console symfony/console symfony/process +``` + +Ориентируйтесь на lock-файл проекта: `composer show` показывает реально разрешённые версии. Пакет не заменяет базовый CLI: Triangle Console расширяет Localzet Console интеграцией с Engine, командами приложения и plugin discovery. + +## Инициализация + +Загружайте Composer autoload и конфигурацию/bootstrapping Triangle Engine до создания `Triangle\Console\Console`. При загруженном Engine Console считывает `config/console.php` и `config/command.php`, ищет классы в `app/command` и включённых плагинах. Готовый project entry point обычно уже делает bootstrap; подключайте Console из него, не создавая второй несогласованный bootstrap. + +Для ручной установки конфигурации используйте `Triangle\Console\Install::install()` в installer-контексте Engine. Метод копирует отсутствующие шаблоны и не перезаписывает пользовательские файлы. После установки сравните созданный `config/console.php` с нужными настройками проекта. diff --git a/src/pages/projects/triangle-console/operations.mdx b/src/pages/projects/triangle-console/operations.mdx new file mode 100644 index 0000000..6d1b7e0 --- /dev/null +++ b/src/pages/projects/triangle-console/operations.mdx @@ -0,0 +1,14 @@ +export const pageTitle = 'Настройка и сборка' +export const description = 'Настройки конфигурации, команды упаковки и ограничения эксплуатации.' + +# Настройка и сборка + +Шаблон `config/console.php` содержит `service.name` и секцию `build`: input/output каталоги, шаблон исключений и список исключаемых файлов, имена PHAR/binary, stub, алгоритм PHAR signature и путь к приватному ключу. `Triangle\Console\Install::install()` не заменяет существующий файл, поэтому обновляйте его вручную после сравнения с новым шаблоном. + +Встроенные команды исходников включают `make:command`, `make:controller`, `make:middleware`, `make:model`, `app:create`, `plugin:create`, `build:phar` и `build:bin`. Точные параметры команды сверяйте через `list` и `help ` установленного entry point. + +## Сборки и секреты + +По умолчанию бинарная конфигурация указывает PHP 8.4 и `memory_limit = 256M`. Расширение `ext-zip` указано как optional для build bin; `ext-openssl` — для PHAR OpenSSL signing. Реально проверьте нужные расширения перед сборкой. Убедитесь, что `.env`, credentials и signing private key не попали в output: шаблон исключает `.env`, но список содержимого всё равно надо проверять. Упаковка не делает исходный код невозможным для извлечения или анализа. + +Храните ключи вне checkout с ограниченным доступом; не передавайте секреты в аргументах CLI, так как они могут быть видны в process list/logs. Проверяйте запуск артефакта в целевой ОС отдельно. diff --git a/src/pages/projects/triangle-console/usage.mdx b/src/pages/projects/triangle-console/usage.mdx new file mode 100644 index 0000000..7871ab7 --- /dev/null +++ b/src/pages/projects/triangle-console/usage.mdx @@ -0,0 +1,43 @@ +export const pageTitle = 'Команды и мост Illuminate' +export const description = 'Создание Symfony-команд, автопоиск и явное подключение команд Illuminate.' + +# Команды и мост Illuminate + +Создайте PSR-4 загружаемый класс команды в `app/command`: + +```php +writeln('Report is ready.'); + return self::SUCCESS; + } +} +``` + +После Engine bootstrap запустите `$console = new Triangle\Console\Console(); exit($console->run());`. Аргументы CLI передаются стандартному `run()`; выполните entry point с `list` или `app:report`. Команды из `config/command.php` — массив имен классов; каждый должен иметь Symfony-compatible `defaultName`. Также выполняется поиск в включённых plugin command каталогах. + +### Illuminate Console + +Мост подключается явно, например при ручном составе приложения: + +```php +$console = (new Triangle\Console\Console([], false)) + ->useIlluminate(new Illuminate\Container\Container()); +$console->addIlluminateCommand(new App\Console\Commands\ReportCommand()); +$console->run(); +``` + +Второй аргумент `false` отключает автоматическую регистрацию внутренних команд пакета. Передайте контейнер, ожидаемый вашими Illuminate-командами. Обычные команды остаются на Symfony API. diff --git a/src/pages/projects/triangle-cron.mdx b/src/pages/projects/triangle-cron.mdx new file mode 100644 index 0000000..c11e044 --- /dev/null +++ b/src/pages/projects/triangle-cron.mdx @@ -0,0 +1,48 @@ +export const pageTitle = 'Triangle Cron' +export const description = 'Регистрация периодических задач в Triangle Engine через отдельный scheduler-процесс.' + +# Triangle Cron + +Triangle Cron подключает планировщик Localzet Cron как отдельный процесс в приложении Triangle Engine. Учитывайте статус релиза: в Packagist опубликован `triangle/cron` **1.0.3**; его ограничения Composer — PHP `^8.1`, Engine `^8.1`, Events `^1.0`, Localzet Cron `^1.0`. Поэтому опубликованный пакет предназначен для старой ветки Engine 8.1. + +Исходники checkout `feat/cron-server7` содержат подготовленную несовместимую ветку 2.x для Engine 9 / Server 7 (`triangle/engine:^9.0`, `localzet/cron:^2.0`), но на момент проверки для неё нет тега/публикации. Не устанавливайте `triangle/cron:^2.0` из Packagist до выхода релиза. Текущие исходники preview не являются содержимым опубликованного 1.0.3. + +## Использование текущего опубликованного пакета + +Для совместимого Engine 8.1 приложения Composer constraint опубликованной линии: + +```sh +composer require triangle/cron:^1.0 +composer show triangle/cron triangle/engine localzet/cron +``` + +Проверьте фактические версии по lock-файлу перед запуском. Не переносите пример Engine 9 ниже на версию 1.0.3 без проверки её README/API. + +## Engine 9 preview: задача и запуск + +Следующий пример описывает только текущую исходную ветку preview, а не установленный релиз: + +```php + 'cleanup-expired-records', + 'rule' => '*/5 * * * *', + 'callback' => static function (): void { + // Keep this task short and non-blocking. + }, + ], +]; +``` + +Preview `Triangle\Cron\Autoload` при управляемой команде запуска регистрирует выделенный `Cron` server с одним worker. На событии старта он читает `config('cron', [])` и создаёт Cron job только для записей, где заданы непустые `rule` и `callback`; `name` необязателен. Пять полей задают расписание с точностью до минуты, шесть могут включать секунды согласно README preview. Callback работает в event loop: передавайте долгие задачи в очередь/отдельный процесс. + +## Надёжность и проверки preview + +Это in-process scheduler, не durable queue: задания и расписание не переживают перезапуск как сохранённое состояние, а отдельные установки приложения не координируют выполнение между собой. Один worker снижает риск запуска каждой задачи всеми workers одного scheduler; несколько инсталляций всё равно требуют внешней координации, если задача должна исполняться ровно в одном месте. + +В preview репозитории `composer run check` запускает PHP lint и `tests/compatibility.php`. Тест проверяет контракт autoload Engine 9, регистрацию выделенного Server 7 процесса и фильтрацию неполных задач. Это не проверка самого расписания под нагрузкой и не доказательство exactly-once. Перед переходом на ветку 2 дождитесь релиза и сверяйте опубликованные constraints и migration notes. + +## Практические руководства + +[Установка](/projects/triangle-cron/install) · [Использование](/projects/triangle-cron/usage) · [Эксплуатация](/projects/triangle-cron/operations) · [Совместимость и тесты](/projects/triangle-cron/compatibility). diff --git a/src/pages/projects/triangle-cron/compatibility.mdx b/src/pages/projects/triangle-cron/compatibility.mdx new file mode 100644 index 0000000..5ca2df7 --- /dev/null +++ b/src/pages/projects/triangle-cron/compatibility.mdx @@ -0,0 +1,16 @@ +export const pageTitle = 'Совместимость и проверки Cron' +export const description = 'Проверка версии 1.0.3 и Engine 9 preview отдельно.' + +# Совместимость и проверки Cron + +Опубликованный v1.0.3 требует PHP `^8.1`, Engine `^8.1`, Events `^1.0`, Localzet Cron `^1.0`. Текущий Engine 9 preview source меняет контракт на Engine `^9.0` и Localzet Cron `^2.0`; его пока нельзя считать опубликованным или совместимым с 1.0.3. Для preview сверяйте текущую ветку и её lock; перед миграцией дождитесь tagged release и опубликованных migration notes. + +В checkout preview доступны: + +```sh +composer install +composer validate --strict --no-check-publish +composer run check +``` + +`check` запускает PHP lint и `tests/compatibility.php`. Тест проверяет Engine autoload contract, регистрацию отдельного Server 7 process и отбор полных task definitions. Он не проверяет фактическое время срабатывания, нагрузку, retry/durability или exactly-once. Опубликованный 1.0.3 и source preview нельзя считать взаимозаменяемыми. diff --git a/src/pages/projects/triangle-cron/en.mdx b/src/pages/projects/triangle-cron/en.mdx new file mode 100644 index 0000000..85e5f4d --- /dev/null +++ b/src/pages/projects/triangle-cron/en.mdx @@ -0,0 +1,48 @@ +export const pageTitle = 'Triangle Cron' +export const description = 'Periodic task registration in Triangle Engine through a dedicated scheduler process.' + +# Triangle Cron + +Triangle Cron integrates Localzet Cron as a separate process in a Triangle Engine application. Release status matters: Packagist publishes `triangle/cron` **1.0.3**, with Composer requirements PHP `^8.1`, Engine `^8.1`, Events `^1.0`, and Localzet Cron `^1.0`. The published package targets the older Engine 8.1 line. + +The checked-out `feat/cron-server7` source contains a prepared, incompatible 2.x line for Engine 9 / Server 7 (`triangle/engine:^9.0`, `localzet/cron:^2.0`), but no tag/publication exists for it at this review. Do not install `triangle/cron:^2.0` from Packagist until that release is published. Preview source is not what the published 1.0.3 package contains. + +## Use the currently published package + +For a compatible Engine 8.1 application, the published Composer constraint is: + +```sh +composer require triangle/cron:^1.0 +composer show triangle/cron triangle/engine localzet/cron +``` + +Check resolved versions in the lock file before running. Do not apply the Engine 9 example below to version 1.0.3 without checking its README/API. + +## Engine 9 preview: task and startup + +The following describes only the current preview source branch, not the published release: + +```php + 'cleanup-expired-records', + 'rule' => '*/5 * * * *', + 'callback' => static function (): void { + // Keep this task short and non-blocking. + }, + ], +]; +``` + +Preview `Triangle\Cron\Autoload` registers a dedicated `Cron` server with one worker for managed startup commands. On server start it reads `config('cron', [])` and creates a Cron job only when both `rule` and `callback` are non-empty; `name` is optional. Five fields provide minute precision; six may include seconds per the preview README. The callback runs on the event loop: send long-running work to a queue or separate process. + +## Preview reliability and checks + +This is an in-process scheduler, not a durable queue: scheduled state is not persisted across restarts, and separate application installations do not coordinate execution. A single worker avoids each worker in one scheduler running every task; multiple installations still need external coordination when only one execution is desired. + +In the preview repository, `composer run check` runs PHP lint and `tests/compatibility.php`. The test checks the Engine 9 autoload contract, dedicated Server 7 process registration, and rejection of incomplete tasks. It does not load-test schedule timing or prove exactly-once execution. Before moving to line 2, wait for a release and verify its published constraints and migration notes. + +## Practical guides + +[Install](/projects/triangle-cron/en/install) · [Usage](/projects/triangle-cron/en/usage) · [Operations](/projects/triangle-cron/en/operations) · [Compatibility and tests](/projects/triangle-cron/en/compatibility). diff --git a/src/pages/projects/triangle-cron/en/compatibility.mdx b/src/pages/projects/triangle-cron/en/compatibility.mdx new file mode 100644 index 0000000..055525a --- /dev/null +++ b/src/pages/projects/triangle-cron/en/compatibility.mdx @@ -0,0 +1,16 @@ +export const pageTitle = 'Cron compatibility and checks' +export const description = 'Keep published v1.0.3 distinct from the Engine 9 preview.' + +# Cron compatibility and checks + +Published v1.0.3 requires PHP `^8.1`, Engine `^8.1`, Events `^1.0`, and Localzet Cron `^1.0`. Current Engine 9 preview source changes the contract to Engine `^9.0` and Localzet Cron `^2.0`; it is not published and should not be treated as compatible with 1.0.3. For preview, check the current branch and lock file. Wait for a tagged release and published migration notes before upgrading. + +The preview checkout provides: + +```sh +composer install +composer validate --strict --no-check-publish +composer run check +``` + +`check` runs PHP lint and `tests/compatibility.php`. The test checks Engine autoload contract, dedicated Server 7 process registration, and filtering of complete task definitions. It does not verify schedule timing, load, retries/durability, or exactly-once behavior. Published 1.0.3 and preview source are not interchangeable. diff --git a/src/pages/projects/triangle-cron/en/install.mdx b/src/pages/projects/triangle-cron/en/install.mdx new file mode 100644 index 0000000..0b5ae29 --- /dev/null +++ b/src/pages/projects/triangle-cron/en/install.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Cron installation and release status' +export const description = 'Published Cron 1.x and the unreleased Engine 9 source line.' + +# Cron installation and release status + +Packagist publishes `triangle/cron` v1.0.3. Its Composer requirements are PHP `^8.1`, Engine `^8.1`, Events `^1.0`, and Localzet Cron `^1.0`. + +```sh +composer require triangle/cron:^1.0 +composer show triangle/cron triangle/engine triangle/events localzet/cron +``` + +This installation is for a compatible Engine 8.1 application. Do not apply the preview examples below to published line 1.x without checking the v1.0.3 source. + +The current checkout with Server 7 changes is beyond tag v1.0.3 and has no published/tagged 2.x release. Its `composer.json` requires Engine `^9.0` and Localzet Cron `^2.0`. `composer require triangle/cron:^2.0` is not an installation command for a published package yet. To evaluate preview source, use that checkout and its manifest/lock; do not treat it as a production release. diff --git a/src/pages/projects/triangle-cron/en/operations.mdx b/src/pages/projects/triangle-cron/en/operations.mdx new file mode 100644 index 0000000..d0053eb --- /dev/null +++ b/src/pages/projects/triangle-cron/en/operations.mdx @@ -0,0 +1,8 @@ +export const pageTitle = 'Cron reliability and operations' +export const description = 'Event loop, processes, and preview scheduler guarantees.' + +# Cron reliability and operations + +The preview runs the scheduler as part of the application's process system; it is not a durable queue. It configures one worker. Increasing the worker count can register duplicate schedules in each worker. Separate installations do not coordinate with one another. Use external coordination/locking for single execution across a cluster if your application provides it; the component does not add this mechanism. + +Do not block the event loop with long SQL/HTTP/CPU work in callbacks. Use an external queue or worker for long-running/retryable tasks and implement idempotency at task level. The source does not persist schedule/execution history as durable job state, so process restart does not restore execution history. Verify error/retry behavior against the exact Localzet Cron version and workload. diff --git a/src/pages/projects/triangle-cron/en/usage.mdx b/src/pages/projects/triangle-cron/en/usage.mdx new file mode 100644 index 0000000..600b203 --- /dev/null +++ b/src/pages/projects/triangle-cron/en/usage.mdx @@ -0,0 +1,23 @@ +export const pageTitle = 'Defining Cron tasks' +export const description = 'Task example for the Engine 9 preview and scheduler startup behavior.' + +# Defining Cron tasks + +The following example applies only to the current Engine 9 preview source: + +```php + 'cleanup-expired-records', + 'rule' => '*/5 * * * *', + 'callback' => static function (): void { + // Add the application task here. + }, + ], +]; +``` + +Place definitions in `config/cron.php`. On managed startup, preview autoload creates a dedicated `Cron` server with one worker. At worker startup it reads `config('cron', [])` and registers only entries with non-empty `rule` and `callback`. `name` is optional. + +Five cron fields provide minute precision; six may include seconds according to the preview documentation. Keep callbacks short and non-blocking; send long-running work to a queue or separate process. Registering a task does not run it immediately during config loading. diff --git a/src/pages/projects/triangle-cron/install.mdx b/src/pages/projects/triangle-cron/install.mdx new file mode 100644 index 0000000..a72a37f --- /dev/null +++ b/src/pages/projects/triangle-cron/install.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Установка и статус выпуска Cron' +export const description = 'Опубликованный Cron 1.x и ограничения ещё не выпущенной ветки Engine 9.' + +# Установка и статус выпуска Cron + +На Packagist опубликован `triangle/cron` v1.0.3. Его Composer requirements: PHP `^8.1`, Engine `^8.1`, Events `^1.0`, Localzet Cron `^1.0`. + +```sh +composer require triangle/cron:^1.0 +composer show triangle/cron triangle/engine triangle/events localzet/cron +``` + +Эта установка предназначена для совместимого Engine 8.1 приложения. Не переносите API и примеры preview ниже на опубликованную линию 1.x без проверки source именно v1.0.3. + +Текущий checkout с изменениями Server 7 находится за тегом v1.0.3, но не имеет опубликованного/помеченного тега 2.x. Его `composer.json` требует Engine `^9.0` и Localzet Cron `^2.0`. `composer require triangle/cron:^2.0` пока не является инструкцией установки опубликованной версии. Для оценки source preview используйте именно checkout и его Composer manifest/lock, не выдавайте это за production release. diff --git a/src/pages/projects/triangle-cron/operations.mdx b/src/pages/projects/triangle-cron/operations.mdx new file mode 100644 index 0000000..23a5466 --- /dev/null +++ b/src/pages/projects/triangle-cron/operations.mdx @@ -0,0 +1,8 @@ +export const pageTitle = 'Надёжность и эксплуатация Cron' +export const description = 'Event loop, процессы и гарантии scheduler preview.' + +# Надёжность и эксплуатация Cron + +Preview запускает scheduler в том же приложении/системе процессов, а не как durable queue. В конфигурации один worker; если увеличить число worker, все они могут зарегистрировать одинаковые задачи. Разные инсталляции отдельно не координируются. Для единственного запуска на кластер используйте внешнюю координацию/lock, если она предусмотрена вашим приложением; компонент её не добавляет. + +Не блокируйте event loop долгим SQL/HTTP/CPU вызовом в callback. Для долгих/повторяемых задач используйте внешнюю очередь или отдельный worker и определяйте idempotency на уровне задачи. Поскольку source не сохраняет расписание/запуски как durable job state, перезапуск процесса не восстанавливает историю выполнений. Точное поведение ошибок/повторов проверяйте в текущей версии Localzet Cron и собственном workload. diff --git a/src/pages/projects/triangle-cron/usage.mdx b/src/pages/projects/triangle-cron/usage.mdx new file mode 100644 index 0000000..e1efe48 --- /dev/null +++ b/src/pages/projects/triangle-cron/usage.mdx @@ -0,0 +1,23 @@ +export const pageTitle = 'Определение задач Cron' +export const description = 'Пример задачи для Engine 9 preview и описание запуска scheduler.' + +# Определение задач Cron + +Следующий фрагмент относится только к текущему Engine 9 preview source: + +```php + 'cleanup-expired-records', + 'rule' => '*/5 * * * *', + 'callback' => static function (): void { + // Add the application task here. + }, + ], +]; +``` + +Поместите определения в `config/cron.php`. Preview autoload на managed startup создаёт отдельный server `Cron` с одним worker; при старте worker читает `config('cron', [])` и регистрирует только записи с непустыми `rule` и `callback`. Поле `name` необязательно. + +Пять полей cron задают минутную точность, шесть могут включать секунды по описанию preview. Прикладной callback должен быть коротким и неблокирующим; длительную работу отправляйте в очередь или отдельный process. Регистрация задачи не означает немедленный запуск при config load. diff --git a/src/pages/projects/triangle-database.mdx b/src/pages/projects/triangle-database.mdx new file mode 100644 index 0000000..357552e --- /dev/null +++ b/src/pages/projects/triangle-database.mdx @@ -0,0 +1,56 @@ +export const pageTitle = 'Triangle Database' +export const description = 'Eloquent и query builder Illuminate для приложений Triangle Engine.' + +# Triangle Database + +Triangle Database интегрирует Illuminate Database с Triangle Engine: загружает Eloquent/query builder и соединения из конфигурации, связывает пагинацию с текущим запросом. Релиз [2.0.0](https://github.com/Triangle-org/Database/releases/tag/v2.0.0). + +Требования: PHP `^8.2`, Engine `^9.0`, Illuminate Database/Events/Pagination `^12.0`, Symfony VarDumper `^7.4`. + +```sh +composer require triangle/database:^2.0 +composer show triangle/database +``` + +## Первое соединение и запрос + +Engine читает `config/database.php`. Минимальный пример SQLite: + +```php +return [ + 'default' => 'sqlite', + 'persistent' => false, + 'connections' => ['sqlite' => [ + 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', + ]], +]; +``` + +Путь к постоянному файлу задаётся в конфиге; шаблон использует `base_path`. `Triangle\Database\Install::install()` копирует конфиг только если файл ещё отсутствует. + +```php +use Triangle\Database\Model; +final class User extends Model { + protected $table = 'users'; + protected $fillable = ['name']; + public $timestamps = false; +} +$user = User::query()->create(['name' => 'Ada']); +$rows = Triangle\Database\Manager::table('users')->where('name', 'Ada')->get(); +``` + +Schema builder доступен через Manager; отдельной migration CLI и автоматического запуска миграций нет. + +## Эксплуатация и безопасность + +Шаблон содержит SQLite/MySQL/PostgreSQL/SQL Server/MongoDB примеры. SQL требует подходящий PDO extension; MongoDB — совместимый адаптер. `persistent` по умолчанию `true`; при старте с Server планируется MySQL keepalive каждые 55 секунд. Это не пул соединений и не гарантия доступности. Установите `persistent=false`, чтобы отключить. Manager и соединения process-local: каждый worker держит собственный экземпляр. + +Пагинаторы Illuminate привязаны к текущему запросу process-wide resolvers; вызывайте их в обработчике, не сохраняйте request-specific данные в долгоживущем состоянии. Используйте минимальные права DB, TLS/таймауты по требованиям драйвера и bindings для raw SQL. Схемы применяйте контролируемой миграцией, не из запроса. + +## Совместимость и проверки + +Тег `v2.0.0` требует Engine 9 и несовместим с Engine 8 и линией пакета 1.x. Обновляйте связанные Triangle компоненты вместе и проверяйте Composer lock. Команда `composer test` использует SQLite in-memory: проверяет bootstrap, создание таблицы, Eloquent insert/read. Она не покрывает внешние DB, production credentials или failover. Mongo адаптер опционален. + +## Практические руководства + +[Установка](/projects/triangle-database/install) · [Использование](/projects/triangle-database/usage) · [Эксплуатация](/projects/triangle-database/operations) · [Совместимость и тесты](/projects/triangle-database/compatibility). diff --git a/src/pages/projects/triangle-database/compatibility.mdx b/src/pages/projects/triangle-database/compatibility.mdx new file mode 100644 index 0000000..6478c40 --- /dev/null +++ b/src/pages/projects/triangle-database/compatibility.mdx @@ -0,0 +1,14 @@ +export const pageTitle = 'Совместимость и тесты Database' +export const description = 'Переход с Engine 8/Database 1 и границы SQLite-проверки.' + +# Совместимость и тесты Database + +Тег `v2.0.0` требует PHP `^8.2`, Engine `^9.0`, Illuminate Database/Events/Pagination `^12.0` и Symfony VarDumper `^7.4`. Линия 2.x несовместима с Engine 8 и пакетом 1.x. Сверьте `composer show triangle/database` и lock-файл, затем обновляйте связанные Triangle компоненты вместе. + +```sh +composer install --no-interaction +composer validate --strict --no-check-publish +composer test +``` + +`composer test` запускает SQLite in-memory regression: bootstrap, создание таблицы и Eloquent insert/read. Он не проверяет удалённые MySQL/PostgreSQL/SQL Server/MongoDB сервисы, production credentials, TLS или failover. Mongo support optional; отдельно проверьте адаптер и конкретную базу в integration environment. diff --git a/src/pages/projects/triangle-database/en.mdx b/src/pages/projects/triangle-database/en.mdx new file mode 100644 index 0000000..b45743e --- /dev/null +++ b/src/pages/projects/triangle-database/en.mdx @@ -0,0 +1,56 @@ +export const pageTitle = 'Triangle Database' +export const description = 'Illuminate Eloquent and query builder for Triangle Engine applications.' + +# Triangle Database + +Triangle Database integrates Illuminate Database with Triangle Engine: it boots Eloquent/query builder and configured connections, and connects pagination to the current request. Release [2.0.0](https://github.com/Triangle-org/Database/releases/tag/v2.0.0). + +Requirements: PHP `^8.2`, Engine `^9.0`, Illuminate Database/Events/Pagination `^12.0`, Symfony VarDumper `^7.4`. + +```sh +composer require triangle/database:^2.0 +composer show triangle/database +``` + +## First connection and query + +Engine reads `config/database.php`. Minimal SQLite example: + +```php +return [ + 'default' => 'sqlite', + 'persistent' => false, + 'connections' => ['sqlite' => [ + 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', + ]], +]; +``` + +Set a file path for persistent SQLite storage; the template uses `base_path`. `Triangle\Database\Install::install()` copies config only when the target file is absent. + +```php +use Triangle\Database\Model; +final class User extends Model { + protected $table = 'users'; + protected $fillable = ['name']; + public $timestamps = false; +} +$user = User::query()->create(['name' => 'Ada']); +$rows = Triangle\Database\Manager::table('users')->where('name', 'Ada')->get(); +``` + +The schema builder is available through Manager; the component has no separate migration CLI and does not run migrations automatically. + +## Operations and security + +The template contains SQLite/MySQL/PostgreSQL/SQL Server/MongoDB examples. SQL requires the matching PDO extension; MongoDB requires a compatible adapter. `persistent` defaults to `true`; when started with Server, a MySQL keepalive is scheduled every 55 seconds. This is not a connection pool or availability guarantee. Set `persistent=false` to disable it. The manager and connections are process-local, so each worker has its own instance. + +Illuminate paginators use process-wide resolvers tied to the current request; call them in request handlers and do not retain request-specific state. Use least-privilege DB accounts, driver-appropriate TLS/timeouts, and bindings for raw SQL. Apply schema changes through a controlled migration process. + +## Compatibility and checks + +Tag `v2.0.0` targets Engine 9 and is incompatible with Engine 8 and package line 1.x. Upgrade related Triangle components together and inspect the Composer lock. `composer test` uses in-memory SQLite to check bootstrap, table creation, and Eloquent insert/read. It does not cover external databases, production credentials, or failover. Mongo integration is optional. + +## Practical guides + +[Install](/projects/triangle-database/en/install) · [Usage](/projects/triangle-database/en/usage) · [Operations](/projects/triangle-database/en/operations) · [Compatibility and tests](/projects/triangle-database/en/compatibility). diff --git a/src/pages/projects/triangle-database/en/compatibility.mdx b/src/pages/projects/triangle-database/en/compatibility.mdx new file mode 100644 index 0000000..e0b1684 --- /dev/null +++ b/src/pages/projects/triangle-database/en/compatibility.mdx @@ -0,0 +1,14 @@ +export const pageTitle = 'Database compatibility and tests' +export const description = 'Upgrade from Engine 8/Database 1 and understand SQLite test coverage.' + +# Database compatibility and tests + +Tag `v2.0.0` requires PHP `^8.2`, Engine `^9.0`, Illuminate Database/Events/Pagination `^12.0`, and Symfony VarDumper `^7.4`. Line 2.x is incompatible with Engine 8 and package line 1.x. Check `composer show triangle/database` and the lock file, then update related Triangle components together. + +```sh +composer install --no-interaction +composer validate --strict --no-check-publish +composer test +``` + +`composer test` runs an in-memory SQLite regression covering bootstrap, table creation, and Eloquent insert/read. It does not test remote MySQL/PostgreSQL/SQL Server/MongoDB services, production credentials, TLS, or failover. Mongo support is optional; validate its adapter and target database separately in an integration environment. diff --git a/src/pages/projects/triangle-database/en/install.mdx b/src/pages/projects/triangle-database/en/install.mdx new file mode 100644 index 0000000..40548b0 --- /dev/null +++ b/src/pages/projects/triangle-database/en/install.mdx @@ -0,0 +1,27 @@ +export const pageTitle = 'Install Triangle Database' +export const description = 'PHP/Illuminate requirements and initial connection setup.' + +# Install Triangle Database + +Triangle Database 2.0.0 requires PHP `^8.2`, Engine `^9.0`, Illuminate Database/Events/Pagination `^12.0`, and Symfony VarDumper `^7.4`. + +```sh +composer require triangle/database:^2.0 +composer show triangle/database triangle/engine illuminate/database illuminate/events illuminate/pagination +``` + +Install the PDO extension for the SQL driver you select. After Engine bootstrap, the package loads `Triangle\Database\Bootstrap`. If the application does not publish config automatically, `Triangle\Database\Install::install()` copies a missing `config/database.php` and leaves an existing file untouched. + +Minimal SQLite connection for a check: + +```php +return [ + 'default' => 'sqlite', + 'persistent' => false, + 'connections' => [ + 'sqlite' => ['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => ''], + ], +]; +``` + +For persistent storage, set `database` to a file path or configure the selected driver. Supply credentials through the environment and keep them out of the repository. diff --git a/src/pages/projects/triangle-database/en/operations.mdx b/src/pages/projects/triangle-database/en/operations.mdx new file mode 100644 index 0000000..6dab052 --- /dev/null +++ b/src/pages/projects/triangle-database/en/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'Database operations and security' +export const description = 'Drivers, per-process connections, migrations, and safe queries.' + +# Database operations and security + +The config template contains SQLite, MySQL, PostgreSQL, SQL Server, and MongoDB examples. SQL connections require the corresponding PDO extensions. MongoDB requires a compatible integration package; it is not a mandatory dependency. + +`persistent` defaults to `true`. When started with Server, the component schedules a MySQL keepalive every 55 seconds. This is not a connection pool, retry policy, or availability guarantee. Set `persistent => false` to disable it. The manager and connections are process-local, so each worker has a separate instance. + +Use a least-privilege DB account, restrict network access, and configure driver-appropriate TLS/timeouts. Bind values in raw SQL; do not concatenate user input. Run migrations as a separate controlled deployment step; bootstrap does not modify the schema automatically. diff --git a/src/pages/projects/triangle-database/en/usage.mdx b/src/pages/projects/triangle-database/en/usage.mdx new file mode 100644 index 0000000..775b768 --- /dev/null +++ b/src/pages/projects/triangle-database/en/usage.mdx @@ -0,0 +1,30 @@ +export const pageTitle = 'Eloquent and the query builder' +export const description = 'Basic model, query, and request-aware pagination examples.' + +# Eloquent and the query builder + +Application models extend `Triangle\Database\Model`: + +```php +create(['name' => 'Ada']); +$found = User::query()->where('id', $user->id)->first(); +$rows = Triangle\Database\Manager::table('users') + ->where('name', 'Ada') + ->get(); +``` + +Use `paginate()`, `simplePaginate()`, or `cursorPaginate()` inside the current HTTP request handler: the component connects Illuminate resolvers to the current request context. Do not retain their parameters/results across requests. The Manager exposes the schema builder, but the package does not include a migration CLI or automatically run migrations. diff --git a/src/pages/projects/triangle-database/install.mdx b/src/pages/projects/triangle-database/install.mdx new file mode 100644 index 0000000..3f9655c --- /dev/null +++ b/src/pages/projects/triangle-database/install.mdx @@ -0,0 +1,27 @@ +export const pageTitle = 'Установка Triangle Database' +export const description = 'Требования PHP/Illuminate и начальная настройка соединения.' + +# Установка Triangle Database + +Triangle Database 2.0.0 требует PHP `^8.2`, Engine `^9.0`, Illuminate Database/Events/Pagination `^12.0` и Symfony VarDumper `^7.4`. + +```sh +composer require triangle/database:^2.0 +composer show triangle/database triangle/engine illuminate/database illuminate/events illuminate/pagination +``` + +Проверьте PDO extension для выбранного SQL driver. После Engine bootstrap пакет загружает `Triangle\Database\Bootstrap`. Если конфигурация не опубликована приложением, `Triangle\Database\Install::install()` копирует отсутствующий `config/database.php`, но не заменяет уже существующий. + +Минимальное SQLite подключение для проверки: + +```php +return [ + 'default' => 'sqlite', + 'persistent' => false, + 'connections' => [ + 'sqlite' => ['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => ''], + ], +]; +``` + +Для постоянной базы задайте `database` как путь к файлу или настройте параметры нужного driver. Секреты передавайте через окружение и держите вне репозитория. diff --git a/src/pages/projects/triangle-database/operations.mdx b/src/pages/projects/triangle-database/operations.mdx new file mode 100644 index 0000000..6adb130 --- /dev/null +++ b/src/pages/projects/triangle-database/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'Эксплуатация и безопасность Database' +export const description = 'Драйверы, соединения по процессам, миграции и безопасные запросы.' + +# Эксплуатация и безопасность Database + +Шаблон конфигурации содержит SQLite, MySQL, PostgreSQL, SQL Server и MongoDB. SQL подключения требуют соответствующих PDO extensions. MongoDB требует совместимого integration package; он не включён в обязательные требования. + +`persistent` по умолчанию `true`. При запуске с Server компонент планирует MySQL keepalive каждые 55 секунд. Это не connection pool, retry policy или гарантия доступности. Установите `persistent => false`, если keepalive не нужен. Manager и connections process-local — каждый worker держит отдельный экземпляр. + +Используйте least-privilege DB аккаунт, ограничьте сетевой доступ, настройте TLS/timeouts по требованиям драйвера. В raw SQL связывайте значения через bindings; не конкатенируйте пользовательский ввод. Миграции запускайте отдельным контролируемым deployment шагом; bootstrap не меняет схему автоматически. diff --git a/src/pages/projects/triangle-database/usage.mdx b/src/pages/projects/triangle-database/usage.mdx new file mode 100644 index 0000000..fbf7dee --- /dev/null +++ b/src/pages/projects/triangle-database/usage.mdx @@ -0,0 +1,30 @@ +export const pageTitle = 'Eloquent и query builder' +export const description = 'Базовый пример модели, запросов и request-aware пагинации.' + +# Eloquent и query builder + +Модель приложения наследует `Triangle\Database\Model`: + +```php +create(['name' => 'Ada']); +$found = User::query()->where('id', $user->id)->first(); +$rows = Triangle\Database\Manager::table('users') + ->where('name', 'Ada') + ->get(); +``` + +Используйте `paginate()`, `simplePaginate()` или `cursorPaginate()` из обработчика текущего HTTP request: компонент подключает Illuminate resolvers к текущему request context. Не кэшируйте их результат/параметры между запросами. Schema builder доступен через Manager, но миграционный CLI и автоматический запуск миграций в пакет не входят. diff --git a/src/pages/projects/triangle-events.mdx b/src/pages/projects/triangle-events.mdx new file mode 100644 index 0000000..cb7aa04 --- /dev/null +++ b/src/pages/projects/triangle-events.mdx @@ -0,0 +1,25 @@ +export const pageTitle = 'Triangle Events 2.0.1 — события в приложении' +export const description = 'Установка Triangle Events 2.0.1, регистрация точных и префиксных обработчиков, конфигурация Engine 9 и ограничения доставки.' + +# Triangle Events + +Triangle Events регистрирует обработчики при запуске Triangle Engine и синхронно вызывает их внутри текущего PHP-процесса. Это диспетчер событий приложения, а не очередь сообщений. + +**Актуальная версия:** 2.0.1 · **PHP:** 8.1+ · **Engine:** 9.x · **Пакет:** `triangle/events`. + +Пакет поддерживает точные имена (`invoice.created`) и подписки на префикс (`invoice.*`). Обработчику передаются payload, затем имя события. События не сохраняются и не передаются между worker-процессами. + +## Быстрый путь + +- [Установка и первый обработчик](triangle-events/install) +- [Регистрация, вызов и результаты обработчиков](triangle-events/usage) +- [Конфигурация, запуск и безопасная эксплуатация](triangle-events/operations) +- [Совместимость, обновление и проверки](triangle-events/compatibility) + +## Когда подходит + +Используйте библиотеку, когда компонентам одного процесса нужно синхронно сообщать о факте (`invoice.created`) без прямой связи между вызывающим кодом и обработчиками. Для фоновой, долговечной или межпроцессной доставки подключайте отдельный брокер/очередь; Events этого не предоставляет. + +## Границы + +Обработчики выполняются в процессе вызова и могут увеличить задержку этого вызова. При `halt: true` диспетчер возвращает первый ненулевой ответ; `false` прекращает обычную последовательную рассылку. В версии 2.0.0 здесь была ошибка инициализации logger. В версии 2.0.1 она исправлена, а регрессионный тест теперь проверяет listener, который выбрасывает исключение. Подробности — в [руководстве по API](triangle-events/usage). diff --git a/src/pages/projects/triangle-events/compatibility.mdx b/src/pages/projects/triangle-events/compatibility.mdx new file mode 100644 index 0000000..c47c08e --- /dev/null +++ b/src/pages/projects/triangle-events/compatibility.mdx @@ -0,0 +1,34 @@ +export const pageTitle = 'Совместимость и тесты Triangle Events' +export const description = 'Совместимость Events 2.0.1 с PHP 8.1 и Engine 9, отличия от прежней ветки и точные проверки.' + +# Совместимость, обновление и проверки + +## Требования версии 2.0.1 + +`triangle/events` 2.0.1 требует PHP `^8.1`, `triangle/engine ^9.0` и `psr/log ^2.0 || ^3.0`. Engine 8 не входит в диапазон совместимости. Если приложение ещё использует Engine 8, сначала планируйте обновление Engine; ограничение зависимости нельзя безопасно обходить принудительной установкой. + +Установка этой версии: + +```sh +composer require triangle/events:^2.0 +composer show triangle/events triangle/engine +``` + +## Изменения в 2.0.1 + +В версии 2.0.0 при исключении listener logger мог использоваться до безопасной инициализации. Версия 2.0.1 исправляет инициализацию и расширяет `tests/engine_compatibility.php`: тест проверяет, что исключение listener возвращается из `emit()` и не выходит наружу. + +## Изменение интеграции + +Ветка 2.x использует bootstrap contract и хуки регистрации конфигурации приложений и плагинов Engine 9. Сверьте `config/event.php` приложения и plugins, затем проверьте запуск на точной версии Engine из lock-файла. Не переносите примеры из старых веток без проверки: API и bootstrap могли отличаться. + +## Проверка исходников + +```sh +composer install +composer test +``` + +Проверка из исходников версии 2.0.1 — `tests/engine_compatibility.php`. Она проверяет совместимость bootstrap-интерфейса, plugin hooks, передачу payload конфигурационному listener и возврат исключения от listener без выхода из `emit()`. Это не нагрузочный тест и не подтверждает доставку между процессами, durable storage, retry или production-метрики. + +**Источники:** [релиз v2.0.1](https://github.com/Triangle-org/Events/tree/v2.0.1), [Composer](https://github.com/Triangle-org/Events/blob/v2.0.1/composer.json), [тест совместимости](https://github.com/Triangle-org/Events/blob/v2.0.1/tests/engine_compatibility.php). diff --git a/src/pages/projects/triangle-events/en.mdx b/src/pages/projects/triangle-events/en.mdx new file mode 100644 index 0000000..01883a9 --- /dev/null +++ b/src/pages/projects/triangle-events/en.mdx @@ -0,0 +1,25 @@ +export const pageTitle = 'Triangle Events 2.0.1 — in-process events' +export const description = 'Triangle Events 2.0.1 installation, exact and prefix listeners, Engine 9 configuration, and delivery limits.' + +# Triangle Events + +Triangle Events registers listeners during Triangle Engine startup and dispatches them synchronously inside the current PHP process. It is an application event dispatcher, not a message queue. + +**Current release:** 2.0.1 · **PHP:** 8.1+ · **Engine:** 9.x · **Package:** `triangle/events`. + +The package supports exact names such as `invoice.created` and prefix subscriptions such as `invoice.*`. Each listener receives the payload followed by the event name. Events are neither persisted nor delivered between worker processes. + +## Guides + +- [Install and register a first listener](triangle-events/en/install) +- [Registration, dispatch, and listener results](triangle-events/en/usage) +- [Configuration, operations, and security](triangle-events/en/operations) +- [Compatibility, upgrades, and checks](triangle-events/en/compatibility) + +## Intended use + +Use this library when components in one process need to react synchronously to an application fact such as `invoice.created`, without direct coupling between the caller and listeners. For background, durable, or cross-process delivery, integrate a separate broker or queue; Events does not provide those features. + +## Limits + +Listeners run before dispatch returns and can add latency to the calling operation. With `halt: true`, the dispatcher returns the first non-null response; `false` stops normal dispatch. Version 2.0.0 had a logger initialization bug on this path. Version 2.0.1 fixes it and adds a regression check with a throwing listener; see the [API guide](triangle-events/en/usage). diff --git a/src/pages/projects/triangle-events/en/compatibility.mdx b/src/pages/projects/triangle-events/en/compatibility.mdx new file mode 100644 index 0000000..32e7084 --- /dev/null +++ b/src/pages/projects/triangle-events/en/compatibility.mdx @@ -0,0 +1,34 @@ +export const pageTitle = 'Triangle Events compatibility and tests' +export const description = 'PHP 8.1 and Engine 9 compatibility, upgrade notes, and checks for Triangle Events 2.0.1.' + +# Compatibility, upgrades, and checks + +## Requirements for 2.0.1 + +`triangle/events` 2.0.1 requires PHP `^8.1`, `triangle/engine ^9.0`, and `psr/log ^2.0 || ^3.0`. Engine 8 is outside the supported dependency range. If an application still uses Engine 8, plan the Engine upgrade first; do not bypass the constraint with a forced install. + +Install this release with: + +```sh +composer require triangle/events:^2.0 +composer show triangle/events triangle/engine +``` + +## Changes in 2.0.1 + +Version 2.0.0 could access the event logger before safe initialization when a listener threw. Version 2.0.1 fixes logger initialization and extends `tests/engine_compatibility.php` to verify that a listener exception is returned and does not escape `emit()`. + +## Integration changes + +The 2.x branch uses the Engine 9 bootstrap contract and hooks for registering application and plugin configuration. Review `config/event.php` in the application and its plugins, then verify startup against the exact Engine version in the lock file. Do not copy examples from older branches without checking them; APIs and bootstrap behavior may differ. + +## Source checks + +```sh +composer install +composer test +``` + +The v2.0.1 source check is `tests/engine_compatibility.php`. It covers the bootstrap interface, plugin hooks, configured-listener payload delivery, and a throwing listener whose exception must be returned without escaping `emit()`. It is not a load test and does not establish cross-process delivery, durable storage, retries, or production metrics. + +**Sources:** [v2.0.1 release](https://github.com/Triangle-org/Events/tree/v2.0.1), [Composer manifest](https://github.com/Triangle-org/Events/blob/v2.0.1/composer.json), [compatibility check](https://github.com/Triangle-org/Events/blob/v2.0.1/tests/engine_compatibility.php). diff --git a/src/pages/projects/triangle-events/en/install.mdx b/src/pages/projects/triangle-events/en/install.mdx new file mode 100644 index 0000000..0c298b2 --- /dev/null +++ b/src/pages/projects/triangle-events/en/install.mdx @@ -0,0 +1,59 @@ +export const pageTitle = 'Install Triangle Events' +export const description = 'Requirements, installation, and a first verifiable example for triangle/events 2.0.1.' + +# Install and register a first listener + +## Requirements + +- PHP 8.1 or later. +- Triangle Engine 9.x. Engine 8 is unsupported because this component uses Engine 9 plugin lifecycle hooks. +- Composer. + +Install the package in an Engine 9 application: + +```sh +composer require triangle/events:^2.0 +``` + +## Dispatch an event + +Use the package-provided `support\Events` facade: + +```php + 42]); +``` + +This is synchronous: `emit()` returns after its listeners finish. Register listeners during application startup or through `config/event.php`, not in code that runs on every request; repeated registration adds repeated callbacks. + +## Application configuration + +Engine bootstrap loads `event.php` for the application and plugin configurations. For example: + +```php + [ + [App\Listeners\InvoiceCreated::class, 'handle'], + ], +]; +``` + +The Engine container resolves configured listener classes. Put this file in the application's configuration directory. The package template at `src/Config/event.php` returns an empty array. + +## Verify + +```sh +composer install +composer test +``` + +The `engine_compatibility.php` check covers the Engine bootstrap contract, plugin reduction hooks, and payload delivery to a configured listener. It does not verify queue deployment or cross-process delivery; the package has no such mechanism. diff --git a/src/pages/projects/triangle-events/en/operations.mdx b/src/pages/projects/triangle-events/en/operations.mdx new file mode 100644 index 0000000..f8c82a0 --- /dev/null +++ b/src/pages/projects/triangle-events/en/operations.mdx @@ -0,0 +1,30 @@ +export const pageTitle = 'Triangle Events configuration and operations' +export const description = 'Application and plugin event.php loading, synchronous execution, error handling, and security limits.' + +# Configuration and operations + +## Loading configuration + +At startup on Engine 9, the Events bootstrap reads the main `event` configuration, followed by equivalent application and plugin configurations. For each `event name => callback list` entry it registers listeners. Invalid structures or non-callable callbacks raise a `RuntimeException` during loading, so validate configuration before production startup. + +```php +return [ + 'report.generated' => [ + [App\Listeners\SendReport::class, 'handle'], + ], +]; +``` + +A plugin may provide its own `config/event.php`. Configured listener classes are resolved through `support\Container`. + +## Execution model + +`emit()` calls callbacks synchronously in the current process. Listener time contributes to the latency of the operation that emitted the event. The dispatcher stores subscriptions in process-local static structures; it does not replicate them across workers or retain events across restarts. + +Use a separate background-processing mechanism for slow I/O, retries, guaranteed delivery, scheduling, or cross-process coordination. Do not include secrets in payloads unless every listener needs them. + +## Errors and security + +A listener exception is included in `emit()` results and is logged when the Engine logging facility is available. This does not make the business operation successful: callers must inspect the result and decide how to handle failure or retry. + +Configuration files and listeners execute as application code. Do not load them from untrusted sources. Events does not implement authorization: callers define the emitted events and payload, and listeners must check their own assumptions and permissions. diff --git a/src/pages/projects/triangle-events/en/usage.mdx b/src/pages/projects/triangle-events/en/usage.mdx new file mode 100644 index 0000000..6f458e2 --- /dev/null +++ b/src/pages/projects/triangle-events/en/usage.mdx @@ -0,0 +1,41 @@ +export const pageTitle = 'Triangle Events API and usage' +export const description = 'Exact and prefix listeners, removal, dispatch order, and the return semantics of Events::emit().' + +# Register and dispatch + +## Exact and prefix listeners + +```php +use support\Events; + +$id = Events::on('user.*', static function (array $data, string $event): void { + // event is, for example, user.created +}); + +Events::on('user.created', static fn (array $data) => audit($data)); +Events::emit('user.created', ['id' => 7]); +Events::off('user.*', $id); +``` + +`*` denotes a prefix only when it is the final character. Matching exact and prefix listeners run in registration order. Each callback receives the data first and the actual event name second. + +## `emit()` results + +By default, `emit($name, $data)` returns an array of listener responses in execution order. The source `catch` branch adds a `Throwable` to this array and continues traversal, but v2.0.0 had a logger initialization bug on this path; v2.0.1 fixes it and adds a regression check with a throwing listener. A listener returning `false` stops subsequent listeners. With `$halt = true`, the method returns the first non-null response, or `null` when none exists. + +```php +$responses = Events::emit('cache.refresh', ['key' => 'catalog']); +$first = Events::emit('permission.check', $subject, true); +``` + +Do not treat `halt` as transaction or guaranteed-delivery semantics. It only stops the synchronous listener traversal. + +## Subscription management + +- `Events::on(string $name, callable|array $listener): int` returns an ID. +- `Events::off(string $name, int $id): int` removes a listener registered under that name; pass the same trailing `*` for a prefix. +- `Events::getListeners(string $name): array` returns matching callbacks. +- `Events::list(): array` lists subscriptions and IDs. +- `Events::hasListener(string $name): bool` checks for matching callbacks. + +An array listener can identify `[ClassName::class, 'method']`; Engine bootstrap resolves configured callbacks through its container. Register valid callables and keep handlers short. Dispatcher exception handling is not a substitute for handling failures in the business operation. diff --git a/src/pages/projects/triangle-events/install.mdx b/src/pages/projects/triangle-events/install.mdx new file mode 100644 index 0000000..a3f7f7f --- /dev/null +++ b/src/pages/projects/triangle-events/install.mdx @@ -0,0 +1,59 @@ +export const pageTitle = 'Установка Triangle Events' +export const description = 'Требования и установка triangle/events 2.0.1, первый запуск и минимальный проверяемый пример.' + +# Установка и первый обработчик + +## Требования + +- PHP 8.1 или новее. +- Triangle Engine 9.x. Engine 8 не поддерживается: компонент использует plugin lifecycle hooks Engine 9. +- Composer. + +Установите пакет в приложение на Engine 9: + +```sh +composer require triangle/events:^2.0 +``` + +## Вызов события + +В приложении используйте фасад `support\Events`, предоставляемый пакетом: + +```php + 42]); +``` + +Это синхронный вызов: `emit()` возвращает управление после выполнения обработчиков. В реальном приложении зарегистрируйте listener при старте приложения либо через `config/event.php`, а не внутри кода, который выполняется на каждый запрос: повторная регистрация создаёт дополнительные вызовы. + +## Конфигурация приложения + +Engine bootstrap загружает `event.php` для приложения и конфигурации плагинов. Пример файла конфигурации: + +```php + [ + [App\Listeners\InvoiceCreated::class, 'handle'], + ], +]; +``` + +Класс listener разрешается через контейнер Engine. Настройте этот файл в каталоге конфигурации приложения; пакет содержит исходный шаблон `src/Config/event.php`, возвращающий пустой массив. + +## Проверка + +```sh +composer install +composer test +``` + +Тест `engine_compatibility.php` проверяет контракт bootstrap с Engine, наличие plugin reduction hooks и передачу payload для обработчика из конфигурации. Он не проверяет развертывание очереди или межпроцессную доставку — таких механизмов в пакете нет. diff --git a/src/pages/projects/triangle-events/operations.mdx b/src/pages/projects/triangle-events/operations.mdx new file mode 100644 index 0000000..c721f61 --- /dev/null +++ b/src/pages/projects/triangle-events/operations.mdx @@ -0,0 +1,30 @@ +export const pageTitle = 'Конфигурация и эксплуатация Triangle Events' +export const description = 'Загрузка event.php в приложении и плагинах, синхронная модель выполнения, ошибки и границы безопасности Events.' + +# Конфигурация и эксплуатация + +## Загрузка конфигурации + +На старте Engine 9 bootstrap Events читает основной массив `event`, затем аналогичные конфигурации приложений и плагинов. Для каждой записи `имя события => список callbacks` bootstrap регистрирует listener. Некорректная структура или невызываемый callback приводит к `RuntimeException` при загрузке, поэтому проверяйте конфигурацию до запуска production. + +```php +return [ + 'report.generated' => [ + [App\Listeners\SendReport::class, 'handle'], + ], +]; +``` + +Плагин может иметь собственный `config/event.php`. Обработчики классов для конфигурации разрешаются через контейнер `support\Container`. + +## Модель выполнения + +`emit()` запускает callbacks синхронно в текущем процессе. Время выполнения listener входит в задержку операции, инициировавшей событие. Диспетчер хранит подписки в статических структурах процесса; он не реплицирует состояние между worker-процессами и не сохраняет сообщения при рестарте. + +Для медленного I/O, повторных попыток, гарантированной доставки, расписания и межпроцессной координации используйте отдельный механизм фоновой обработки. Не помещайте в payload секреты, если они не нужны всем подписчикам. + +## Ошибки и безопасность + +Исключение listener включается в результаты `emit()` и, если доступен logging Engine, записывается в журнал. Это не делает бизнес-операцию успешной: вызывающий код должен анализировать возвращаемое значение и отдельно принимать решение о retry/ошибке. + +Конфигурационные файлы и сами listeners исполняются как код приложения. Не загружайте их из недоверенных источников. Авторизация не входит в Events: передаваемые события и payload контролирует вызывающий код, а обработчики должны проверять собственные предпосылки и права. diff --git a/src/pages/projects/triangle-events/usage.mdx b/src/pages/projects/triangle-events/usage.mdx new file mode 100644 index 0000000..7030356 --- /dev/null +++ b/src/pages/projects/triangle-events/usage.mdx @@ -0,0 +1,41 @@ +export const pageTitle = 'API и сценарии Triangle Events' +export const description = 'Точные и префиксные подписки, снятие listener, порядок вызова и семантика результата Events::emit().' + +# Регистрация и вызов + +## Точная и префиксная подписка + +```php +use support\Events; + +$id = Events::on('user.*', static function (array $data, string $event): void { + // event is, for example, user.created +}); + +Events::on('user.created', static fn (array $data) => audit($data)); +Events::emit('user.created', ['id' => 7]); +Events::off('user.*', $id); +``` + +Символ `*` задаёт префикс только в конце имени. Совпавшие точные и префиксные listeners вызываются в порядке регистрации. Подпись callback: сначала передаваемые данные, затем фактическое имя события. + +## Результат `emit()` + +По умолчанию `emit($name, $data)` возвращает массив ответов в порядке выполнения. Ветка `catch` исходника добавляет `Throwable` в этот массив и продолжает обход, но в v2.0.0 здесь была ошибка инициализации logger. В v2.0.1 она исправлена, а тест дополнен listener, который выбрасывает исключение. Если listener возвращает `false`, последующие обработчики не вызываются. При `$halt = true` метод возвращает первый ненулевой ответ, либо `null`, если такого ответа не было. + +```php +$responses = Events::emit('cache.refresh', ['key' => 'catalog']); +$first = Events::emit('permission.check', $subject, true); +``` + +Не используйте `halt` как транзакционную или гарантирующую доставку семантику: это только остановка синхронного обхода listeners. + +## Управление подписками + +- `Events::on(string $name, callable|array $listener): int` возвращает ID. +- `Events::off(string $name, int $id): int` снимает обработчик указанного имени; для префикса передайте то же имя с `*`. +- `Events::getListeners(string $name): array` возвращает совпадающие callbacks. +- `Events::list(): array` перечисляет подписки и их ID. +- `Events::hasListener(string $name): bool` проверяет наличие совпадающих callbacks. + +В массиве listener можно указать `[ClassName::class, 'method']`; Engine bootstrap для конфигурационных callbacks получает экземпляр через контейнер. Передавайте валидные callbacks и держите обработчики короткими: исключения из самого dispatch не заменяют обработку ошибок бизнес-операции. diff --git a/src/pages/projects/triangle-middleware.mdx b/src/pages/projects/triangle-middleware.mdx new file mode 100644 index 0000000..ec2c80e --- /dev/null +++ b/src/pages/projects/triangle-middleware.mdx @@ -0,0 +1,54 @@ +export const pageTitle = 'Triangle Middleware' +export const description = 'HTTP middleware-компонент Triangle: конфигурация цепочек приложения, плагинов, маршрутов и контроллеров.' + +# Triangle Middleware + +Triangle Middleware предоставляет общий контракт обработчика и загрузчик middleware для приложений Triangle. Он собирает списки из конфигурации приложения и плагинов, а также из маршрута и атрибутов контроллера. Вызов цепочки и преобразование результата в HTTP response выполняет интеграция приложения, например Triangle HTTP; этот пакет сам по себе не является HTTP-сервером. + +Опубликованный релиз — [2.0.3](https://github.com/Triangle-org/Middleware/releases/tag/v2.0.3). Требования: PHP `^8.1`, `triangle/router:^2.0`, `triangle/engine:^8.1 || ^9.0`. Текущий checkout `2eade42` — четыре коммита после релизного тега; он сохраняет эти constraints и добавляет CI/regression checks, которых нет в самом теге. + +```sh +composer require triangle/middleware:^2.0 +composer show triangle/middleware triangle/engine triangle/router +``` + +## Контракт middleware + +```php + [RequestLogMiddleware::class], + 'api' => [ApiAccessMiddleware::class], +]; +``` + +Ключ `@` означает глобальный уровень, пустой ключ — уровень приложения по умолчанию, ключ `api` — named app. Bootstrap также собирает статические middleware Engine и конфигурацию приложений/плагинов. Маршруты могут добавлять middleware через router; атрибут `#[Triangle\Annotation\Middleware(SomeMiddleware::class)]` доступен на классе/методе контроллера, также читается публичное default-свойство `middleware` контроллера. Класс атрибута входит в Engine. + +`Bootstrap::getMiddleware($plugin, $app, $controller, $route, $withGlobal)` возвращает подготовленные callable-методы `process`; при `withGlobal: false` глобальные элементы опускаются. Список кэшируется в статическом состоянии процесса: повторная загрузка в том же процессе дополняет состояние, а не очищает его. Проверяйте фактический порядок в вашей интеграции перед зависимостью от порядка побочных эффектов. + +## Проверки и ограничения + +В текущем checkout доступны `composer lint` и `composer test`; они добавлены после опубликованного v2.0.3. Regression suite проверяет scopes global/plugin/app middleware, исключение global через `withGlobal: false`, неверную структуру и отсутствие `process`. Сама suite отсутствует в release tag и не запускает полный HTTP request/response цикл. Для этого добавьте integration test в приложение с теми версиями Engine, Router и HTTP, которые реально развёрнуты. Не используйте middleware как место для долгих блокирующих операций в event-loop обработчике. + +## Практические руководства + +[Установка](/projects/triangle-middleware/install) · [Использование](/projects/triangle-middleware/usage) · [Эксплуатация](/projects/triangle-middleware/operations) · [Совместимость и тесты](/projects/triangle-middleware/compatibility). diff --git a/src/pages/projects/triangle-middleware/compatibility.mdx b/src/pages/projects/triangle-middleware/compatibility.mdx new file mode 100644 index 0000000..c095947 --- /dev/null +++ b/src/pages/projects/triangle-middleware/compatibility.mdx @@ -0,0 +1,16 @@ +export const pageTitle = 'Совместимость и тесты Middleware' +export const description = 'Условия опубликованного v2.0.3 и покрытие loader regression suite.' + +# Совместимость и тесты Middleware + +Опубликованный v2.0.3 допускает PHP `^8.1`, Router `^2.0` и Engine `^8.1 || ^9.0`. Проверьте совместимость Server/HTTP request types в конкретном приложении; сам интерфейс не диктует типизацию payload. + +Текущий checkout `2eade42` находится на четыре коммита после тега. Его `composer.json`, тесты и CI включают проверки, которых нет в опубликованном v2.0.3; для самого релиза эти scripts запускать нельзя, если их нет в установленном пакете. + +```sh +composer validate --no-check-publish --no-interaction +composer lint +composer test +``` + +В preview checkout доступны regression checks для scopes global/plugin/app, `withGlobal: false`, malformed config и класса без `process`. Их нет в теге v2.0.3. Проверки не запускают полную HTTP обработку или middleware реального приложения. После обновления проверьте собственный порядок вызова, атрибуты и обработку ответа интеграционным тестом. diff --git a/src/pages/projects/triangle-middleware/en.mdx b/src/pages/projects/triangle-middleware/en.mdx new file mode 100644 index 0000000..d8f0dfa --- /dev/null +++ b/src/pages/projects/triangle-middleware/en.mdx @@ -0,0 +1,54 @@ +export const pageTitle = 'Triangle Middleware' +export const description = 'Triangle HTTP middleware component for application, plugin, route, and controller chains.' + +# Triangle Middleware + +Triangle Middleware provides a middleware contract and loader for Triangle applications. It collects lists from application/plugin configuration, routes, and controller attributes. The application integration (for example Triangle HTTP) invokes the chain and converts results to HTTP responses; this package is not an HTTP server by itself. + +Published release: [2.0.3](https://github.com/Triangle-org/Middleware/releases/tag/v2.0.3). Requirements: PHP `^8.1`, `triangle/router:^2.0`, and `triangle/engine:^8.1 || ^9.0`. The current checkout at `2eade42` is four commits beyond the release tag; it keeps these constraints and adds CI/regression checks that are absent from the tag. + +```sh +composer require triangle/middleware:^2.0 +composer show triangle/middleware triangle/engine triangle/router +``` + +## Middleware contract + +```php + [RequestLogMiddleware::class], + 'api' => [ApiAccessMiddleware::class], +]; +``` + +`@` is global scope, an empty key is the default application scope, and `api` names an application. Bootstrap also collects Engine static middleware and application/plugin configuration. Routes may add middleware through Router; `#[Triangle\Annotation\Middleware(SomeMiddleware::class)]` is available on controller classes/methods, and a public default `middleware` property is read as well. The attribute class is provided by Engine. + +`Bootstrap::getMiddleware($plugin, $app, $controller, $route, $withGlobal)` returns callable `process` entries; `withGlobal: false` omits global entries. The list is cached in process-static state: loading again in the same process appends rather than resets it. Verify the actual order in the integration before relying on side-effect order. + +## Checks and limits + +The current checkout provides `composer lint` and `composer test`; these scripts were added after published v2.0.3. Its regression suite checks global/plugin/application scope, `withGlobal: false`, malformed config, and missing `process`. The suite is absent from the release tag and does not run a full HTTP request/response cycle. Add an application integration test using the actual Engine, Router, and HTTP versions you deploy. Avoid long blocking work in middleware executed by an event loop. + +## Practical guides + +[Install](/projects/triangle-middleware/en/install) · [Usage](/projects/triangle-middleware/en/usage) · [Operations](/projects/triangle-middleware/en/operations) · [Compatibility and tests](/projects/triangle-middleware/en/compatibility). diff --git a/src/pages/projects/triangle-middleware/en/compatibility.mdx b/src/pages/projects/triangle-middleware/en/compatibility.mdx new file mode 100644 index 0000000..909d2ab --- /dev/null +++ b/src/pages/projects/triangle-middleware/en/compatibility.mdx @@ -0,0 +1,16 @@ +export const pageTitle = 'Middleware compatibility and tests' +export const description = 'Published v2.0.3 constraints and loader regression coverage.' + +# Middleware compatibility and tests + +Published v2.0.3 allows PHP `^8.1`, Router `^2.0`, and Engine `^8.1 || ^9.0`. Verify Server/HTTP request types in the consuming application; the interface itself does not type the payload. + +The current checkout at `2eade42` is four commits beyond the tag. Its Composer scripts, tests, and CI checks are not part of published v2.0.3; do not assume those commands exist in the installed release. + +```sh +composer validate --no-check-publish --no-interaction +composer lint +composer test +``` + +The preview checkout regression suite checks global/plugin/app scopes, `withGlobal: false`, malformed config, and a class without `process`; the v2.0.3 tag does not contain this suite. It does not run a complete HTTP request or the application's real middleware. After upgrades, test chain order, attributes, and response handling with an integration test. diff --git a/src/pages/projects/triangle-middleware/en/install.mdx b/src/pages/projects/triangle-middleware/en/install.mdx new file mode 100644 index 0000000..6ad84e2 --- /dev/null +++ b/src/pages/projects/triangle-middleware/en/install.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Install Middleware' +export const description = 'Install the package and check its compatibility constraints.' + +# Install Middleware + +Published `triangle/middleware` v2.0.3 requires PHP `^8.1`, `triangle/router:^2.0`, and `triangle/engine:^8.1 || ^9.0`. + +```sh +composer require triangle/middleware:^2.0 +composer show triangle/middleware triangle/router triangle/engine +``` + +The package is a loader and middleware contract, not a standalone HTTP runtime. Engine starts the bootstrap with Server. An HTTP integration such as Triangle HTTP must invoke the chain and use request/response types compatible with the application. + +The package config template `config/middleware.php` starts with an empty list. Add middleware to the Engine application's config and inspect the resolved lock file; this package does not create a universal request handler. diff --git a/src/pages/projects/triangle-middleware/en/operations.mdx b/src/pages/projects/triangle-middleware/en/operations.mdx new file mode 100644 index 0000000..b5d2eac --- /dev/null +++ b/src/pages/projects/triangle-middleware/en/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'Middleware operations and security' +export const description = 'Configuration validation, process state, and HTTP contract boundaries.' + +# Middleware operations and security + +Each config value must be a list of classes, and each class must have a `process` method. The loader does not require the interface, but implementing it helps static checks. A malformed shape or missing method throws `RuntimeException`. + +Middleware storage is process-static. Calling `load()` again appends entries and does not clear old ones. Do not reload configuration in a long-lived worker unless process state is intentionally reset or the worker is restarted. + +`MiddlewareInterface::process($request, callable $handler)` does not type request/response and does not use PSR-15 `RequestHandlerInterface`; do not assume strict PSR-7/15 compatibility. Validate inputs in middleware, avoid long blocking work on an event loop, and define error responses in the HTTP integration. Configure and test CORS/auth policy at the application boundary. diff --git a/src/pages/projects/triangle-middleware/en/usage.mdx b/src/pages/projects/triangle-middleware/en/usage.mdx new file mode 100644 index 0000000..58da369 --- /dev/null +++ b/src/pages/projects/triangle-middleware/en/usage.mdx @@ -0,0 +1,32 @@ +export const pageTitle = 'Registering and ordering Middleware' +export const description = 'Create a process handler, configure scopes, and attach middleware to routes/controllers.' + +# Registering and ordering Middleware + +Middleware receives a request and a callable for the next handler, then returns the downstream result or its own response: + +```php + [AccessLog::class], + 'api' => [ApiAccess::class], +]; +``` + +The loader also collects plugin and Engine static config. Router supplies route middleware. The Engine attribute can be placed on a class/method: `#[Triangle\Annotation\Middleware(AccessLog::class)]`; a public default controller `middleware` property is also read. + +`Triangle\Middleware\Bootstrap::getMiddleware($plugin, $app, $controller, $route, $withGlobal)` returns `process` callables to the integrator. `withGlobal: false` excludes global middleware. Which entry executes first depends on how the HTTP integration folds the list into a chain; verify the order with an application test. diff --git a/src/pages/projects/triangle-middleware/install.mdx b/src/pages/projects/triangle-middleware/install.mdx new file mode 100644 index 0000000..114a99f --- /dev/null +++ b/src/pages/projects/triangle-middleware/install.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Установка Middleware' +export const description = 'Установите пакет и проверьте ограничения совместимости.' + +# Установка Middleware + +Опубликованный `triangle/middleware` v2.0.3 требует PHP `^8.1`, `triangle/router:^2.0` и `triangle/engine:^8.1 || ^9.0`. + +```sh +composer require triangle/middleware:^2.0 +composer show triangle/middleware triangle/router triangle/engine +``` + +Пакет — загрузчик и контракт middleware, а не самостоятельный HTTP runtime. Bootstrap запускается Engine при старте Server. Для вызова HTTP цепочки нужна интеграция, например Triangle HTTP, совместимая с типом request/response приложения. + +Пакет конфигурации поставляет шаблон `config/middleware.php` с пустым массивом. В Engine приложении добавьте middleware в конфиг и проверьте установленный lock; сам пакет не создаёт универсальный request handler. diff --git a/src/pages/projects/triangle-middleware/operations.mdx b/src/pages/projects/triangle-middleware/operations.mdx new file mode 100644 index 0000000..4e5df81 --- /dev/null +++ b/src/pages/projects/triangle-middleware/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'Эксплуатация и безопасность Middleware' +export const description = 'Валидация конфигурации, состояние процесса и границы HTTP-контракта.' + +# Эксплуатация и безопасность Middleware + +В массиве конфигурации каждая запись должна быть списком классов, а класс — иметь `process`. Наличие интерфейса загрузчиком не требуется, но реализация интерфейса помогает статически проверить ваш код. Некорректная структура или отсутствующий метод приводят к `RuntimeException`. + +Middleware storage кэшируется статически в процессе. Повторный вызов `load()` добавляет записи и не очищает старые. Поэтому не пытайтесь reload-ить конфиг в долгоживущем worker без контролируемого перезапуска/сброса процесса. + +`MiddlewareInterface::process($request, callable $handler)` не типизирует request/response и не использует PSR-15 `RequestHandlerInterface`; не считайте его строгой PSR-7/15 совместимостью. Валидируйте входные данные в middleware, не блокируйте event loop долгими операциями и явно определяйте ошибочный ответ в HTTP интеграции. Любая CORS/auth политика должна быть настроена и проверена на конечном приложении. diff --git a/src/pages/projects/triangle-middleware/usage.mdx b/src/pages/projects/triangle-middleware/usage.mdx new file mode 100644 index 0000000..a929210 --- /dev/null +++ b/src/pages/projects/triangle-middleware/usage.mdx @@ -0,0 +1,32 @@ +export const pageTitle = 'Регистрация и порядок Middleware' +export const description = 'Создайте process handler, задайте уровни и подключите middleware к маршруту/контроллеру.' + +# Регистрация и порядок Middleware + +Middleware принимает request и callable следующего обработчика, а затем возвращает downstream результат или собственный response: + +```php + [AccessLog::class], + 'api' => [ApiAccess::class], +]; +``` + +Загрузчик также собирает plugin и Engine static config. Route middleware приходит через Router. Атрибут Engine можно задать на class/method: `#[Triangle\Annotation\Middleware(AccessLog::class)]`; также учитывается публичное default-свойство controller `middleware`. + +`Triangle\Middleware\Bootstrap::getMiddleware($plugin, $app, $controller, $route, $withGlobal)` отдаёт методы `process` для интегратора. `withGlobal: false` пропускает global middleware. Список, фактически применяемый первым/последним, зависит от того, как HTTP интеграция сворачивает его в chain — зафиксируйте порядок тестом в своём приложении. diff --git a/src/pages/projects/triangle-oauth.mdx b/src/pages/projects/triangle-oauth.mdx new file mode 100644 index 0000000..2cfb7a4 --- /dev/null +++ b/src/pages/projects/triangle-oauth.mdx @@ -0,0 +1,59 @@ +export const pageTitle = 'Triangle OAuth' +export const description = 'OAuth 1, OAuth 2 и OpenID адаптеры провайдеров с callback и хранилищем состояния.' + +# Triangle OAuth + +Triangle OAuth предоставляет менеджер провайдеров и адаптеры OAuth 1, OAuth 2 и OpenID. Опубликован [`v3.0.9`](https://github.com/Triangle-org/OAuth/releases/tag/v3.0.9). Composer-пакет `triangle/oauth` требует PHP `^8.2`, ext-mbstring/json/curl и `localzet/http:^2.0`. В текущем checkout manifest дополнительно требует `triangle/engine:^8.1`; он находится на четыре коммита после тега, поэтому это требование текущего исходного состояния, а не метаданные опубликованного v3.0.9. + +Локальный checkout `gc66280e` — preview после тега, не отдельный опубликованный релиз. Сверяйте требования выбранного источника: release package и checkout имеют разные Composer constraints. + +```sh +composer require triangle/oauth:^3.0 +composer show triangle/oauth localzet/http +``` + +В текущем Engine-приложении проверьте Composer разрешение и доступность request/session helpers до использования. Для Apple в manifest как optional dependencies указаны `localzet/jwt` и `phpseclib/phpseclib`; Steam требует ext-libxml и ext-simplexml. + +## Инициализация и flow + +Менеджеру передаётся массив конфигурации или путь к PHP-файлу, а также optional storage/logger. Например для Google: + +```php +$config = [ + 'callback' => 'https://app.example.test/oauth/google', + 'providers' => [ + 'google' => [ + 'enabled' => true, + 'keys' => ['id' => getenv('GOOGLE_CLIENT_ID'), 'secret' => getenv('GOOGLE_CLIENT_SECRET')], + 'scope' => 'https://www.googleapis.com/auth/userinfo.profile', + ], + ], +]; +$oauth = new \Triangle\OAuth($config); +$result = $oauth->authenticate('google'); +if ($result instanceof \Triangle\Engine\Response) { + return $result; // redirect response during the authorization start +} +$profile = $result->getUserProfile(); +``` + +Это демонстрация API, а не готовый controller: обработчик callback должен вызывать тот же manager с тем же provider config в пользовательской сессии. Для исходящего шага `authenticate()` возвращает redirect response; после возврата provider callback завершает обмен code на token и возвращает adapter. Провайдеры включаются явно через `enabled`; `callback` можно задать глобально или переопределить в provider config. Пример класса `Google` доступен в исходниках; каталог содержит также GitHub, Microsoft, Apple, Steam и другие адаптеры. Наличие класса не означает, что у каждого провайдера одинаковые scopes, поля профиля или дополнительные зависимости. + +Manager также предоставляет `getProviders()`, `getConnectedProviders()`, `getConnectedAdapters()`, `isConnectedWith()` и `disconnectAllAdapters()`. Возможности API профиля и контактов зависят от конкретного адаптера. + +## Хранение, безопасность и пределы + +По умолчанию адаптер использует `Triangle\OAuth\Storage\Session`; она сохраняет token/state в текущую сессию и вызывает `session()->save()`. Можно передать собственный `StorageInterface`. OAuth2 поддерживает state по умолчанию и сверяет callback state с сохранённым значением; конфигурация может отключить это поведение. Текущая генерация state в исходниках использует `str_shuffle`, поэтому не считайте встроенный state криптографически стойкой защитой. Для production оцените замену/усиление state generation и обязательно сохраняйте и проверяйте state в доверенном session store. + +Храните client secrets вне исходников, ограничьте scopes, используйте HTTPS callback и не логируйте tokens/секреты. Session storage восстанавливает сериализованные object значения через `unserialize`; не используйте недоверенное/подменяемое хранилище без оценки риска. Успешная библиотечная авторизация не заменяет локальную проверку прав пользователя в приложении. + +## Совместимость и проверки + +Тег v3.0.9 manifest отличается от текущего checkout Engine constraint: публикация требует перечисленные PHP extensions и `localzet/http:^2.0`, checkout ещё объявляет Engine `^8.1`. Сверяйте `composer show` и lock перед установкой в Engine приложении. В checkout не найден test directory и нет composer test/lint scripts; отдельный automated test command не заявлен. Проверьте реальные provider redirect/callback flows в интеграционном окружении и на тестовых OAuth credentials. + +## Практические руководства + +- [Установка и первый OAuth flow](triangle-oauth/install) +- [Старт авторизации, callback и профиль](triangle-oauth/usage) +- [Сессии, секреты и границы безопасности](triangle-oauth/operations) +- [Версии, совместимость и проверки](triangle-oauth/compatibility) diff --git a/src/pages/projects/triangle-oauth/compatibility.mdx b/src/pages/projects/triangle-oauth/compatibility.mdx new file mode 100644 index 0000000..90e3ef1 --- /dev/null +++ b/src/pages/projects/triangle-oauth/compatibility.mdx @@ -0,0 +1,23 @@ +export const pageTitle = 'Совместимость и проверки Triangle OAuth' +export const description = 'Различия published v3.0.9 и текущего preview checkout, ограничения тестов и проверка integrations.' + +# Версии, совместимость и проверки + +## Релиз и preview — разные состояния + +| Источник | Ревизия | PHP и основные зависимости | +| --- | --- | --- | +| Published release | `v3.0.9` | PHP `^8.2`, `localzet/http:^2.0`, ext-mbstring/json/curl; Engine не объявлен в runtime `require` тега | +| Current checkout preview | `gc66280e` (4 commits after tag) | те же требования плюс `triangle/engine:^8.1` | + +Установка опубликованной версии: `composer require triangle/oauth:^3.0`. Текущий checkout не является релизом; сверяйте commit и Composer lock отдельно. + +## Автоматические проверки + +В `composer.json` нет test/lint scripts и в checkout нет тестового каталога. CI в текущей ветке проверяет manifest/lock, устанавливает зависимости без scripts, запускает синтаксический `php -l`, а тесты запускает условно только при наличии Composer test script. Поэтому интеграционные OAuth flows, callback state, provider API и секреты не проверяются автоматическими тестами пакета. + +## Ручной integration checklist + +На отдельном provider app проверьте: redirect на provider, отказ пользователя, callback с неверным/пропущенным state, успешный обмен authorization code, сохранение session между запросами, истёкший/отозванный token и выдачу минимально необходимых profile fields. Выполняйте эти проверки на staging credentials, не публикуя tokens. + +Источники: [tag v3.0.9 manifest](https://github.com/Triangle-org/OAuth/blob/v3.0.9/composer.json), [preview commit `gc66280e`](https://github.com/Triangle-org/OAuth/commit/gc66280e), [OAuth2 state handling](https://github.com/Triangle-org/OAuth/blob/gc66280e/src/OAuth/Adapter/OAuth2.php). diff --git a/src/pages/projects/triangle-oauth/en.mdx b/src/pages/projects/triangle-oauth/en.mdx new file mode 100644 index 0000000..3427ada --- /dev/null +++ b/src/pages/projects/triangle-oauth/en.mdx @@ -0,0 +1,59 @@ +export const pageTitle = 'Triangle OAuth' +export const description = 'OAuth 1, OAuth 2, and OpenID provider adapters with callback handling and state storage.' + +# Triangle OAuth + +Triangle OAuth provides a provider manager and OAuth 1, OAuth 2, and OpenID adapters. Published tag: [`v3.0.9`](https://github.com/Triangle-org/OAuth/releases/tag/v3.0.9). The published `triangle/oauth` Composer package requires PHP `^8.2`, ext-mbstring/json/curl, and `localzet/http:^2.0`. The current checkout additionally requires `triangle/engine:^8.1`; it is four commits beyond the tag, so this is a current source constraint, not metadata for published v3.0.9. + +The local checkout at `gc66280e` is an untagged preview after the release, not a separate published version. Check constraints for the exact source you install: the release package and checkout have different Composer requirements. + +```sh +composer require triangle/oauth:^3.0 +composer show triangle/oauth localzet/http +``` + +In an Engine application, verify resolved dependencies and availability of request/session helpers before use. The manifest lists `localzet/jwt` and `phpseclib/phpseclib` as optional for Apple; Steam requires ext-libxml and ext-simplexml. + +## Initialize and run the flow + +Pass the manager an array or PHP config path, with optional storage/logger. Example for Google: + +```php +$config = [ + 'callback' => 'https://app.example.test/oauth/google', + 'providers' => [ + 'google' => [ + 'enabled' => true, + 'keys' => ['id' => getenv('GOOGLE_CLIENT_ID'), 'secret' => getenv('GOOGLE_CLIENT_SECRET')], + 'scope' => 'https://www.googleapis.com/auth/userinfo.profile', + ], + ], +]; +$oauth = new \Triangle\OAuth($config); +$result = $oauth->authenticate('google'); +if ($result instanceof \Triangle\Engine\Response) { + return $result; // redirect response during the authorization start +} +$profile = $result->getUserProfile(); +``` + +This demonstrates the API, not a complete controller: the callback handler must call the manager with the same provider config and user's session. On the authorization start, `authenticate()` returns a redirect response; after the provider redirects back, callback handling exchanges the code and returns an adapter. Enable providers explicitly with `enabled`; set `callback` globally or per provider. The source includes Google, GitHub, Microsoft, Apple, Steam, and other adapter classes. Class presence does not imply identical scopes, profile fields, or extra dependencies for every provider. + +The manager also exposes `getProviders()`, `getConnectedProviders()`, `getConnectedAdapters()`, `isConnectedWith()`, and `disconnectAllAdapters()`. Profile/contact API support depends on the provider adapter. + +## Storage, security, and limits + +By default adapters use `Triangle\OAuth\Storage\Session`, which stores token/state in the current session and calls `session()->save()`. A custom `StorageInterface` can be injected. OAuth2 state support is enabled by default and callback state is compared with stored state; config can disable this. Current source generates state with `str_shuffle`, so do not treat the built-in generation as cryptographically strong protection. For production, assess replacing/hardening state generation and keep state in a trusted session store. + +Keep client secrets out of source, limit scopes, use HTTPS callbacks, and do not log tokens/secrets. Session storage restores serialized object values with `unserialize`; do not use an untrusted or tamperable store without assessing this risk. Successful provider authentication does not replace application-level authorization checks. + +## Compatibility and checks + +The v3.0.9 tag manifest differs from the current checkout's Engine constraint: the published package requires the listed PHP extensions and `localzet/http:^2.0`, while checkout also declares Engine `^8.1`. Inspect `composer show` and the lock file when integrating with Engine. No test directory or Composer test/lint scripts were found in the checkout, so no package-provided automated check is declared. Verify actual provider redirects/callbacks in an integration environment with test OAuth credentials. + +## Practical guides + +- [Install and run a first OAuth flow](triangle-oauth/en/install) +- [Authorization start, callback, and profile](triangle-oauth/en/usage) +- [Sessions, secrets, and security boundaries](triangle-oauth/en/operations) +- [Versions, compatibility, and checks](triangle-oauth/en/compatibility) diff --git a/src/pages/projects/triangle-oauth/en/compatibility.mdx b/src/pages/projects/triangle-oauth/en/compatibility.mdx new file mode 100644 index 0000000..169894f --- /dev/null +++ b/src/pages/projects/triangle-oauth/en/compatibility.mdx @@ -0,0 +1,23 @@ +export const pageTitle = 'Triangle OAuth compatibility and checks' +export const description = 'Differences between published v3.0.9 and the current preview checkout, CI checks, and integration coverage.' + +# Versions, compatibility, and checks + +## Release and preview are separate states + +| Source | Revision | PHP and main requirements | +| --- | --- | --- | +| Published release | `v3.0.9` | PHP `^8.2`, `localzet/http:^2.0`, ext-mbstring/json/curl; Engine is not in the tag's runtime `require` | +| Current checkout preview | `gc66280e` (4 commits after tag) | same requirements plus `triangle/engine:^8.1` | + +Install the published release with `composer require triangle/oauth:^3.0`. The current checkout is not a release; inspect its commit and Composer lock separately. + +## Automated checks + +The checkout has no Composer `test`/`lint` scripts and no test directory. Current CI validates the manifest/lock, installs locked dependencies without scripts, runs PHP syntax checks, and conditionally runs tests only when a Composer test script exists. Provider redirects, callback state, remote API behavior, and credential handling are not covered by package tests. + +## Manual integration checklist + +With a separate provider app, verify the redirect, user denial, callback with missing or invalid state, authorization-code exchange, session continuity across requests, expired/revoked tokens, and only the required profile fields. Use staging credentials and never publish tokens. + +Sources: [v3.0.9 tag manifest](https://github.com/Triangle-org/OAuth/blob/v3.0.9/composer.json), [preview commit `gc66280e`](https://github.com/Triangle-org/OAuth/commit/gc66280e), [OAuth2 state handling](https://github.com/Triangle-org/OAuth/blob/gc66280e/src/OAuth/Adapter/OAuth2.php). diff --git a/src/pages/projects/triangle-oauth/en/install.mdx b/src/pages/projects/triangle-oauth/en/install.mdx new file mode 100644 index 0000000..248e6ce --- /dev/null +++ b/src/pages/projects/triangle-oauth/en/install.mdx @@ -0,0 +1,27 @@ +export const pageTitle = 'Install Triangle OAuth 3.0.9' +export const description = 'Install triangle/oauth, inspect published release requirements, and distinguish the current preview checkout.' + +# Install and start an OAuth flow + +## Published release + +Tag `v3.0.9` is published as Composer package `triangle/oauth`. It requires PHP `^8.2`, `ext-mbstring`, `ext-json`, `ext-curl`, and `localzet/http:^2.0`. + +```sh +composer require triangle/oauth:^3.0 +composer show triangle/oauth localzet/http +``` + +The v3.0.9 tag does not declare Engine as a runtime dependency, although the code uses Engine request/session/response APIs and support logging. Verify integration with your application; a successful Composer resolution alone does not prove runtime compatibility. + +## Current checkout preview + +The current source checkout is commit `gc66280e`, four commits after v3.0.9. Its manifest additionally requires `triangle/engine:^8.1`; this is an untagged preview, not the published release's constraint. + +If you need this exact source, pin the revision in a private mirror or path repository and verify its lock file. Do not silently substitute the current branch for tag v3.0.9. + +## Provider setup + +Create an OAuth application with the provider and register an exact HTTPS callback URL. Supply the client ID and secret through environment variables and request only required scopes. Composer lists `localzet/jwt` and `phpseclib/phpseclib` as optional for Apple; Steam needs `ext-libxml` and `ext-simplexml`. + +The package declares no `test` or `lint` script. The current CI validates Composer metadata, installs locked dependencies, and runs `php -l`; this does not exercise an external OAuth redirect/callback flow. diff --git a/src/pages/projects/triangle-oauth/en/operations.mdx b/src/pages/projects/triangle-oauth/en/operations.mdx new file mode 100644 index 0000000..97f64f0 --- /dev/null +++ b/src/pages/projects/triangle-oauth/en/operations.mdx @@ -0,0 +1,20 @@ +export const pageTitle = 'Triangle OAuth operations and security' +export const description = 'OAuth state and token storage, callback checks, credential protection, and adapter API limits.' + +# Sessions, secrets, and security + +## Session and storage + +When no `StorageInterface` is injected, adapters use `Triangle\OAuth\Storage\Session`. Values are stored in the current session under the `OAuthStorage` namespace, and writes call `session()->save()`. The callback must receive the same session that held the authorization state. A custom storage implementation must follow `StorageInterface` and protect values against disclosure or tampering. + +Session storage serializes objects and calls `unserialize()` when restoring them. Do not use a store that an untrusted party can modify. Clear tokens on disconnect and at local-session termination according to the application's policy. + +## State and callback + +OAuth2 adapters store and compare state by default. The `supportRequestState` setting can disable this check; keep it enabled for browser authorization flows. Current source generates state with `str_shuffle`, so it should not be treated as cryptographically strong. This is a material limitation for public production login: verify state protection and use a secure unpredictable nonce in the chosen integration before release. + +Validate callback URLs, provider errors, and one-time state matching; do not accept arbitrary redirect destinations from query parameters. Use HTTPS and the exact redirect URI registered with the provider. + +## Credentials and access + +Keep client secrets in an environment or secret store. Exclude tokens, authorization codes, state, and secrets from logs and errors. Request minimum scopes. A successful provider response establishes an external identity according to that provider's model; the application assigns local roles and permissions. diff --git a/src/pages/projects/triangle-oauth/en/usage.mdx b/src/pages/projects/triangle-oauth/en/usage.mdx new file mode 100644 index 0000000..8fb134b --- /dev/null +++ b/src/pages/projects/triangle-oauth/en/usage.mdx @@ -0,0 +1,40 @@ +export const pageTitle = 'Triangle OAuth authorization and callback' +export const description = 'Configure a provider, separate authorization start from callback handling, and retrieve a user profile.' + +# Start authorization and handle the callback + +Construct the manager with a configuration array or PHP file path, plus optional storage and logger. A provider must be listed in `providers` and explicitly enabled. + +```php +$config = [ + 'callback' => 'https://app.example.test/oauth/google/callback', + 'providers' => [ + 'google' => [ + 'enabled' => true, + 'keys' => [ + 'id' => getenv('GOOGLE_CLIENT_ID'), + 'secret' => getenv('GOOGLE_CLIENT_SECRET'), + ], + 'scope' => 'https://www.googleapis.com/auth/userinfo.profile', + ], + ], +]; +$oauth = new \Triangle\OAuth($config); +$result = $oauth->authenticate('google'); +``` + +On the authorization-start request, `authenticate()` returns a `Triangle\Engine\Response` redirect; return it from the Engine handler. On callback, process the request with the same provider configuration and user's session context. A successful callback returns the provider adapter: + +```php +$result = $oauth->authenticate('google'); +if ($result instanceof \Triangle\Engine\Response) { + return $result; +} + +$profile = $result->getUserProfile(); +// Map $profile->identifier to a local account. +``` + +This shows the response branch, not a complete controller. The application must provide the callback route, session cookie, provider-denial handling, and local identity mapping. Do not link accounts on email alone without validating the trust model. + +Profile/contact methods depend on the specific adapter. Do not assume providers share scopes or profile fields. diff --git a/src/pages/projects/triangle-oauth/install.mdx b/src/pages/projects/triangle-oauth/install.mdx new file mode 100644 index 0000000..f605e80 --- /dev/null +++ b/src/pages/projects/triangle-oauth/install.mdx @@ -0,0 +1,27 @@ +export const pageTitle = 'Установка Triangle OAuth 3.0.9' +export const description = 'Установка triangle/oauth, зависимости опубликованного релиза и проверка текущего preview checkout.' + +# Установка и первый OAuth flow + +## Опубликованный релиз + +Тег `v3.0.9` опубликован как Composer-пакет `triangle/oauth`. Требуются PHP `^8.2`, `ext-mbstring`, `ext-json`, `ext-curl` и `localzet/http:^2.0`. + +```sh +composer require triangle/oauth:^3.0 +composer show triangle/oauth localzet/http +``` + +Выпуск v3.0.9 не объявляет Engine как runtime dependency в манифесте тега, хотя код использует Engine request/session/response API и support logging. Проверяйте фактическую интеграцию своего приложения, а не только успешное разрешение Composer. + +## Текущий checkout и preview + +Текущая копия исходников — commit `gc66280e`, четыре коммита после v3.0.9. Её manifest уже включает `triangle/engine:^8.1`; это untagged preview, а не constraint опубликованного релиза. + +Если задача требует именно этот исходник, зафиксируйте точную ревизию в собственном mirror/path repository и проверяйте его lock-файл. Не подменяйте тег v3.0.9 текущей веткой незаметно. + +## Подготовка провайдера + +Создайте OAuth application у выбранного провайдера и задайте точный HTTPS callback URL. Идентификатор и secret передавайте из переменных окружения, а scopes ограничьте необходимыми правами. Для Apple в Composer указаны optional `localzet/jwt` и `phpseclib/phpseclib`; для Steam требуются `ext-libxml` и `ext-simplexml`. + +Пакет не объявляет скрипт `test` или `lint`. В текущем CI выполняются Composer validation, установка lock-зависимостей и `php -l`; это не проверяет внешний OAuth redirect/callback flow. diff --git a/src/pages/projects/triangle-oauth/operations.mdx b/src/pages/projects/triangle-oauth/operations.mdx new file mode 100644 index 0000000..30a2ff7 --- /dev/null +++ b/src/pages/projects/triangle-oauth/operations.mdx @@ -0,0 +1,20 @@ +export const pageTitle = 'Эксплуатация и безопасность Triangle OAuth' +export const description = 'Хранение OAuth state и токенов, callback validation, защита credentials и ограничения adapter API.' + +# Сессии, секреты и безопасность + +## Сессия и storage + +Без переданного `StorageInterface` adapter использует `Triangle\\OAuth\\Storage\\Session`. Данные лежат в текущей сессии под namespace `OAuthStorage`; запись вызывает `session()->save()`. Callback должен получить ту же сессию, в которой был создан authorization state. Для собственной реализации storage соблюдайте контракт `StorageInterface` и защитите данные от чтения/подмены. + +Session storage сериализует объекты, а при чтении вызывает `unserialize()`. Не используйте хранилище, которое может быть изменено недоверенной стороной. Удаляйте/очищайте токены при disconnect и завершении локальной сессии по правилам приложения. + +## State и callback + +OAuth2 adapter по умолчанию сохраняет state и сравнивает его с callback параметром. Параметр `supportRequestState` может отключить эту проверку; не выключайте её для браузерного authorization flow. Текущая генерация state в исходниках использует `str_shuffle`, поэтому её нельзя считать криптографически надёжной. Для публичного production login это существенное ограничение: проверьте state protection и используйте безопасный непредсказуемый nonce в выбранной интеграции до публикации. + +Проверяйте callback URL, provider errors и одноразовое сопоставление `state`; не принимайте произвольные redirect destinations из query. Используйте HTTPS и точный redirect URI, зарегистрированный у провайдера. + +## Секреты и права + +Храните client secret только в secret store/окружении; исключайте токены, authorization codes, state и секреты из журналов и ошибок. Просите минимальные scopes. Успешный ответ провайдера подтверждает только внешний identity согласно модели провайдера; локальную роль и доступ назначает приложение. diff --git a/src/pages/projects/triangle-oauth/usage.mdx b/src/pages/projects/triangle-oauth/usage.mdx new file mode 100644 index 0000000..1a25b0f --- /dev/null +++ b/src/pages/projects/triangle-oauth/usage.mdx @@ -0,0 +1,40 @@ +export const pageTitle = 'OAuth авторизация и callback Triangle OAuth' +export const description = 'Конфигурация провайдера, разделение начала OAuth flow и callback, получение профиля пользователя.' + +# Начало авторизации и callback + +Менеджер создаётся с массивом конфигурации либо путём к PHP-файлу, optional storage и logger. Провайдер должен быть указан в `providers` и явно включён через `enabled`. + +```php +$config = [ + 'callback' => 'https://app.example.test/oauth/google/callback', + 'providers' => [ + 'google' => [ + 'enabled' => true, + 'keys' => [ + 'id' => getenv('GOOGLE_CLIENT_ID'), + 'secret' => getenv('GOOGLE_CLIENT_SECRET'), + ], + 'scope' => 'https://www.googleapis.com/auth/userinfo.profile', + ], + ], +]; +$oauth = new \Triangle\OAuth($config); +$result = $oauth->authenticate('google'); +``` + +На authorization-start request `authenticate()` возвращает `Triangle\Engine\Response` с redirect; верните этот response из Engine handler. При callback обработайте запрос тем же provider config и тем же пользовательским session context. Успешный callback возвращает provider adapter: + +```php +$result = $oauth->authenticate('google'); +if ($result instanceof \Triangle\Engine\Response) { + return $result; +} + +$profile = $result->getUserProfile(); +// Сопоставьте $profile->identifier с локальной учётной записью. +``` + +Пример показывает ветвление ответа, но не является полным controller: приложение должно обеспечить корректный callback route, session cookie, обработку отказа провайдера и собственное сопоставление identity. Не связывайте учётные записи только по email без отдельной проверки модели доверия. + +Поддержка profile/contact методов зависит от конкретного adapter. Не переносите scopes и поля профиля одного провайдера на другой. diff --git a/src/pages/projects/triangle-router.mdx b/src/pages/projects/triangle-router.mdx new file mode 100644 index 0000000..3e1fee9 --- /dev/null +++ b/src/pages/projects/triangle-router.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Triangle Router 2.0.7 — маршрутизация HTTP' +export const description = 'Triangle Router 2.0.7: маршруты и параметры, standalone dispatcher, Engine bootstrap, методы HTTP и границы ответственности.' + +# Triangle Router + +Triangle Router сопоставляет HTTP-метод и путь с обработчиком и параметрами маршрута. Библиотека может работать как самостоятельный dispatcher либо подключаться к Triangle Engine через bootstrap; эти два способа настройки различаются. + +**Версия:** 2.0.7 · **PHP:** 8.1+ · **Engine:** `^8.1 || ^9.0` · **Пакет:** `triangle/router`. + +- [Установка и самостоятельный dispatcher](triangle-router/install) +- [Шаблоны маршрутов и результаты dispatch](triangle-router/usage) +- [Интеграция Engine и эксплуатация](triangle-router/operations) +- [Совместимость, безопасность и тесты](triangle-router/compatibility) + +Маршрутизатор определяет, какой обработчик соответствует запросу. Само совпадение маршрута не авторизует пользователя и не формирует HTTP-ответ. Приложение отвечает за проверку доступа, нормализацию метода/URI, статусы 404/405 и `Allow`, а также требуемую семантику HEAD. diff --git a/src/pages/projects/triangle-router/compatibility.mdx b/src/pages/projects/triangle-router/compatibility.mdx new file mode 100644 index 0000000..48501cf --- /dev/null +++ b/src/pages/projects/triangle-router/compatibility.mdx @@ -0,0 +1,30 @@ +export const pageTitle = 'Совместимость и тесты Triangle Router' +export const description = 'Ограничения Router 2.0.7, заметки по обновлению, PHPUnit команды и фактическая область тестов.' + +# Совместимость, безопасность и тесты + +## Требования версии 2.0.7 + +Пакет требует PHP `^8.1` и Triangle Engine `^8.1 || ^9.0`; PHPUnit 10.5 указан для разработки. Установка: + +```sh +composer require triangle/router:^2.0 +composer show triangle/router triangle/engine +``` + +Если используются Engine route configs, проверьте расположение `config/route.php`, конфигурацию плагинов и bootstrap компонентов. Если приложение использует standalone helpers, проверьте вызов dispatcher и собственную нормализацию URI отдельно. + +## Тесты + +```sh +composer install +composer test +``` + +Скрипт запускает PHPUnit с `tests/phpunit.xml`; тесты `tests/Unit/RouteTest.php` проверяют построение/разбор маршрутов. Эти тесты не подтверждают авторизацию, отправку 404/405/HEAD ответов или соответствие нормализации URI конкретному production server. + +## Обновление и границы + +Перед обновлением проверьте changelog и сравните конфигурационные маршруты, имена и callbacks. Не меняйте одновременно regex-парсер и логику авторизации без отдельного теста маршрута и access-control проверки. + +**Источники:** [релиз v2.0.7](https://github.com/Triangle-org/Router/tree/v2.0.7), [Composer](https://github.com/Triangle-org/Router/blob/v2.0.7/composer.json), [unit tests](https://github.com/Triangle-org/Router/tree/v2.0.7/tests/Unit). diff --git a/src/pages/projects/triangle-router/en.mdx b/src/pages/projects/triangle-router/en.mdx new file mode 100644 index 0000000..ba0f726 --- /dev/null +++ b/src/pages/projects/triangle-router/en.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Triangle Router 2.0.7 — HTTP routing' +export const description = 'Triangle Router 2.0.7 guide: route patterns and parameters, standalone dispatch, Engine bootstrap, HTTP methods, and responsibility boundaries.' + +# Triangle Router + +Triangle Router matches an HTTP method and path to a handler and route parameters. It can run as a standalone dispatcher or integrate with Triangle Engine through its bootstrap; these setup paths are distinct. + +**Version:** 2.0.7 · **PHP:** 8.1+ · **Engine:** `^8.1 || ^9.0` · **Package:** `triangle/router`. + +- [Install and create a standalone dispatcher](triangle-router/en/install) +- [Route patterns and dispatch results](triangle-router/en/usage) +- [Engine integration and operations](triangle-router/en/operations) +- [Compatibility, security, and tests](triangle-router/en/compatibility) + +The router selects a matching handler. A route match does not authorize a user or create an HTTP response. The application is responsible for access checks, method and URI normalization, 404/405 responses and the `Allow` header, and required HEAD semantics. diff --git a/src/pages/projects/triangle-router/en/compatibility.mdx b/src/pages/projects/triangle-router/en/compatibility.mdx new file mode 100644 index 0000000..229dc20 --- /dev/null +++ b/src/pages/projects/triangle-router/en/compatibility.mdx @@ -0,0 +1,30 @@ +export const pageTitle = 'Triangle Router compatibility and tests' +export const description = 'Triangle Router 2.0.7 limits, upgrade notes, PHPUnit commands, and actual test coverage.' + +# Compatibility, security, and tests + +## Requirements for 2.0.7 + +The package requires PHP `^8.1` and Triangle Engine `^8.1 || ^9.0`; PHPUnit 10.5 is a development dependency. + +```sh +composer require triangle/router:^2.0 +composer show triangle/router triangle/engine +``` + +If using Engine route configuration, verify `config/route.php`, plugin configuration, and component bootstrap. If the application uses standalone helpers, verify dispatcher invocation and your own URI normalization separately. + +## Tests + +```sh +composer install +composer test +``` + +The script runs PHPUnit with `tests/phpunit.xml`; `tests/Unit/RouteTest.php` checks route construction and parsing. These tests do not establish authorization, 404/405/HEAD response behavior, or URI normalization for a particular production server. + +## Upgrades and scope + +Before upgrading, review the changelog and compare configured routes, names, and callbacks. Avoid changing the regular-expression parser and authorization logic at the same time without a route test and an access-control check. + +**Sources:** [v2.0.7 release](https://github.com/Triangle-org/Router/tree/v2.0.7), [Composer manifest](https://github.com/Triangle-org/Router/blob/v2.0.7/composer.json), [unit tests](https://github.com/Triangle-org/Router/tree/v2.0.7/tests/Unit). diff --git a/src/pages/projects/triangle-router/en/install.mdx b/src/pages/projects/triangle-router/en/install.mdx new file mode 100644 index 0000000..2bb6972 --- /dev/null +++ b/src/pages/projects/triangle-router/en/install.mdx @@ -0,0 +1,44 @@ +export const pageTitle = 'Install and start Triangle Router' +export const description = 'Triangle Router 2.0.7 requirements and a minimal standalone dispatcher with a parameterized route.' + +# Install and create a standalone dispatcher + +Requirements: PHP 8.1+, Composer, and Triangle Engine `^8.1 || ^9.0`. + +```sh +composer require triangle/router:^2.0 +``` + +Composer autoloads `simpleRouteDispatcher()`. A minimal standalone example: + +```php +addRoute('GET', '/users/{id:\\d+}', static function (array $params): string { + return 'user ' . $params['id']; + }); +}); + +$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: '/'; +$path = rawurldecode($path); +$result = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], $path); + +if ($result[0] === Dispatcher::FOUND) { + [$status, $handler, $params] = $result; + $body = $handler($params); + // Create and send an HTTP response in the application. +} +``` + +The dispatcher returns match information. It does not call a string handler or write an HTTP response for the application. The application must normalize the URI for its server environment and convert the result into a response. + +Run the package tests: + +```sh +composer test +``` diff --git a/src/pages/projects/triangle-router/en/operations.mdx b/src/pages/projects/triangle-router/en/operations.mdx new file mode 100644 index 0000000..6ca5d8e --- /dev/null +++ b/src/pages/projects/triangle-router/en/operations.mdx @@ -0,0 +1,32 @@ +export const pageTitle = 'Triangle Router integration and operations' +export const description = 'Differences between standalone and Engine bootstrap, route.php configuration, URI normalization, authorization, and HTTP responses.' + +# Integration and operations + +## Standalone and Engine modes + +In standalone mode, the application builds `simpleRouteDispatcher()` or `cachedRouteDispatcher()` and passes normalized HTTP method and path values to it. The functions return a dispatcher whose result the application handles itself. + +Engine bootstrap is separate: `Triangle\Router\Bootstrap` collects routes from `config/route.php` and active plugin configurations when a server object is available. A route file can use the static facade, for example: + +```php + response('ok')); +``` + +Do not mix standalone data-generator/dispatcher configuration with Engine bootstrap, which collects route configuration and builds its Engine dispatcher. + +## Trust and access control + +A route is a match rule, not an access policy. Perform authentication and authorization in application middleware or handlers. Protect administrative routes regardless of how specific their paths are. + +A standalone caller must separate the query string from the path and select normalization and decoding appropriate to its server environment. Do not decode a URI multiple times: ambiguous normalization can cause authorization checks and route matching to disagree. + +## HTTP semantics + +The dispatcher reports `NOT_FOUND`, `METHOD_NOT_ALLOWED`, or `FOUND`; the application decides which response to create. For 405, return `Allow`. Do not assume that registering GET provides the required HEAD behavior: register the needed method or handle it explicitly, and verify response body and headers. + +The router is not a complete HTTP stack, service-discovery system, authorization system, or replacement for the application's response middleware. diff --git a/src/pages/projects/triangle-router/en/usage.mdx b/src/pages/projects/triangle-router/en/usage.mdx new file mode 100644 index 0000000..254f3e3 --- /dev/null +++ b/src/pages/projects/triangle-router/en/usage.mdx @@ -0,0 +1,33 @@ +export const pageTitle = 'Triangle Router route definitions and dispatch' +export const description = 'HTTP methods, parameters, optional segments, groups, and FOUND, NOT_FOUND, and METHOD_NOT_ALLOWED results.' + +# Define routes + +## Methods and parameters + +```php +$router->addRoute(['GET', 'POST'], '/users/{id:\\d+}', $handler); +$router->addGroup('/api', static function (Triangle\Router $router): void { + $router->addRoute('GET', '/users/{id}', $showUser); +}); +``` + +`$handler` must be callable (or a valid `[ClassName::class, 'method']` pair); a descriptive string alone is not a valid handler. + +The standard parser uses `{name}` for a segment that does not contain `/`; a custom regular expression can be written as `{id:\\d+}`. Optional segments use square brackets at the end of a pattern, such as `/articles[/{id}]`; an optional segment in the middle is unsupported. Groups add a shared prefix. + +The Router class also provides `get`, `post`, `put`, `patch`, `delete`, `head`, `options`, and `any` shortcuts. `resource()` creates resource routes for controller actions. Check the exact methods and route names in the API for your version. + +## Read dispatch results + +`dispatch($method, $path)` returns an array with one of these statuses: + +- `Dispatcher::FOUND`: `[FOUND, $handler, $params]`. +- `Dispatcher::NOT_FOUND`: no route matched. +- `Dispatcher::METHOD_NOT_ALLOWED`: the second item contains allowed HTTP methods. + +For 405, the application should return an `Allow` header listing the allowed methods. The dispatcher does not create responses for 404 or 405. For `FOUND`, the application resolves the callback and passes parameters according to its own contract. + +## Cached standalone dispatcher + +`cachedRouteDispatcher($definition, ['cacheFile' => $path])` saves generated route data to a PHP file and reuses it on the next startup unless `cacheDisabled` is enabled. Place the cache in a directory writable by the application but not served over HTTP; never accept this PHP file's contents from a user. diff --git a/src/pages/projects/triangle-router/install.mdx b/src/pages/projects/triangle-router/install.mdx new file mode 100644 index 0000000..5320698 --- /dev/null +++ b/src/pages/projects/triangle-router/install.mdx @@ -0,0 +1,44 @@ +export const pageTitle = 'Установка и первый запуск Triangle Router' +export const description = 'Требования Triangle Router 2.0.7 и минимальный самостоятельный dispatcher с маршрутом и параметром.' + +# Установка и самостоятельный dispatcher + +Требуются PHP 8.1+, Composer и Triangle Engine `^8.1 || ^9.0`. + +```sh +composer require triangle/router:^2.0 +``` + +Функция `simpleRouteDispatcher()` доступна через Composer autoload. Минимальный standalone пример: + +```php +addRoute('GET', '/users/{id:\\d+}', static function (array $params): string { + return 'user ' . $params['id']; + }); +}); + +$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: '/'; +$path = rawurldecode($path); +$result = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], $path); + +if ($result[0] === Dispatcher::FOUND) { + [$status, $handler, $params] = $result; + $body = $handler($params); + // Create and send an HTTP response in the application. +} +``` + +Dispatcher отдаёт информацию о совпадении. Он не вызывает строковый handler за приложение и не пишет HTTP-ответ за него. Нормализацию URI под свою серверную среду и преобразование результата в ответ выполняет приложение. + +Запустите тесты пакета: + +```sh +composer test +``` diff --git a/src/pages/projects/triangle-router/operations.mdx b/src/pages/projects/triangle-router/operations.mdx new file mode 100644 index 0000000..eb66f9a --- /dev/null +++ b/src/pages/projects/triangle-router/operations.mdx @@ -0,0 +1,32 @@ +export const pageTitle = 'Интеграция и эксплуатация Triangle Router' +export const description = 'Отличия standalone и Engine bootstrap, конфигурация route.php, нормализация URI, авторизация и HTTP-ответы.' + +# Интеграция и эксплуатация + +## Самостоятельный режим и Engine + +В standalone-режиме приложение строит `simpleRouteDispatcher()` или `cachedRouteDispatcher()` и само передаёт ему нормализованные HTTP method и path. Функции возвращают dispatcher, чьи результаты приложение обрабатывает самостоятельно. + +Engine bootstrap — отдельный путь: `Triangle\Router\Bootstrap` при наличии объекта сервера собирает маршруты из `config/route.php` и активных конфигураций плагинов. Файл маршрутов использует статический фасад, например: + +```php + response('ok')); +``` + +Не смешивайте standalone настройку data generator/dispatcher с Engine bootstrap, который сам собирает маршрутные конфиги и создаёт Engine dispatcher. + +## Доверие и контроль доступа + +Маршрут — это сопоставление, а не политика доступа. Проверяйте аутентификацию и авторизацию в middleware/обработчике приложения. Ограничивайте доступ к административным маршрутам независимо от того, насколько специфичен их путь. + +Standalone caller должен отделить query string от path и выбрать корректную нормализацию/декодирование под используемую серверную среду. Не декодируйте URI несколько раз: неоднозначная нормализация может привести к несовпадению проверки доступа и маршрута. + +## HTTP-семантика + +Dispatcher сообщает `NOT_FOUND`, `METHOD_NOT_ALLOWED` или `FOUND`; приложение решает, какой response сформировать. Для 405 передайте клиенту `Allow`. Не предполагайте, что регистрация GET автоматически определяет требуемое поведение HEAD: зарегистрируйте нужный метод или обработайте его явно и проверьте тело/заголовки ответа. + +Маршрутизатор не является заменой полного HTTP stack, service discovery, authorization system или response middleware приложения. diff --git a/src/pages/projects/triangle-router/usage.mdx b/src/pages/projects/triangle-router/usage.mdx new file mode 100644 index 0000000..edb8d0a --- /dev/null +++ b/src/pages/projects/triangle-router/usage.mdx @@ -0,0 +1,33 @@ +export const pageTitle = 'Определение и разрешение маршрутов Triangle Router' +export const description = 'Методы, параметры, необязательные сегменты, группы и ответы FOUND, NOT_FOUND, METHOD_NOT_ALLOWED.' + +# Определение маршрутов + +## Методы и параметры + +```php +$router->addRoute(['GET', 'POST'], '/users/{id:\\d+}', $handler); +$router->addGroup('/api', static function (Triangle\Router $router): void { + $router->addRoute('GET', '/users/{id}', $showUser); +}); +``` + +`$handler` must be callable (or a valid `[ClassName::class, 'method']` pair); a descriptive string alone is not a valid handler. + +Стандартный parser использует `{name}` для сегмента без `/`; пользовательский regex задаётся как `{id:\\d+}`. Необязательные сегменты задаются квадратными скобками в конце шаблона, например `/articles[/{id}]`; необязательная часть посреди маршрута не поддерживается. Группы добавляют общий префикс. + +Класс Router также предоставляет shortcuts `get`, `post`, `put`, `patch`, `delete`, `head`, `options` и `any`; `resource()` генерирует ресурсные маршруты для действий контроллера. Проверяйте точные методы и имена маршрутов в API вашей версии. + +## Разбор результата + +`dispatch($method, $path)` возвращает массив с одним из статусов: + +- `Dispatcher::FOUND`: `[FOUND, $handler, $params]`. +- `Dispatcher::NOT_FOUND`: маршрут не найден. +- `Dispatcher::METHOD_NOT_ALLOWED`: второй элемент содержит допустимые HTTP-методы. + +При 405 приложение должно сформировать заголовок `Allow` со списком допустимых методов. При 404 и 405 dispatcher не создаёт response сам. Для `FOUND` приложение разрешает callback и передаёт параметры ему в соответствии со своим контрактом. + +## Кэшируемый standalone dispatcher + +`cachedRouteDispatcher($definition, ['cacheFile' => $path])` сохраняет сгенерированную структуру маршрутов в PHP-файл и использует её при следующем старте, если `cacheDisabled` не включён. Размещайте кэш в каталоге, доступном приложению на запись и недоступном для HTTP-раздачи; не принимайте содержимое такого PHP-файла от пользователя. diff --git a/src/pages/projects/triangle-session.mdx b/src/pages/projects/triangle-session.mdx new file mode 100644 index 0000000..01fa5c0 --- /dev/null +++ b/src/pages/projects/triangle-session.mdx @@ -0,0 +1,42 @@ +export const pageTitle = 'Triangle Session' +export const description = 'HTTP-сессии Triangle Engine с файловым, Redis, Redis Cluster и MongoDB хранилищем.' + +# Triangle Session + +Triangle Session подключает HTTP-сессии Localzet Server к Triangle Engine и предоставляет helper `session()` для текущего запроса. Релиз [2.0.0](https://github.com/Triangle-org/Session/releases/tag/v2.0.0). + +Требования: PHP `^8.1`, Engine `^9.0`; Engine 9 требует API сессий Server 7.1+. + +```sh +composer require triangle/session:^2.0 +composer show triangle/session +``` + +## Использование + +Engine загружает `Triangle\Session\Bootstrap` автоматически. Если приложение не публикует config, `Triangle\Session\Install::install()` копирует отсутствующий шаблон. + +```php +session(['user_id' => 42, 'preferences' => ['theme' => 'dark']]); +$userId = session('user_id'); +$theme = session('preferences.theme', 'light'); +$currentSession = session(); +``` + +Без аргумента helper возвращает session текущего запроса; строковый ключ читает, массив записывает. Храните скаляры/массивы: объекты из сериализованного хранилища не инстанцируются. + +## Хранилище, cookie и безопасность + +По умолчанию `SESSION_TYPE=file`, путь — `runtime_path('sessions')`. Поддерживаются `file`, `redis`, `redis_cluster`, `mongo`; Redis требует ext-redis, Mongo требует `mongodb/mongodb` и ext-mongodb. Настройки находятся под `session.config.`. + +Cookie defaults: `PHPSID`, HTTP-only включён, secure выключен, пустые domain и SameSite. Для HTTPS задайте `SESSION_COOKIE_SECURE=true`; настройте domain и SameSite согласно origins и cross-site сценарию. `SESSION_LIFETIME` и `SESSION_COOKIE_LIFETIME` независимы. + +Сессия относится к запросу, не worker-процессу. Не удерживайте объект сессии в долгоживущем состоянии. Несколько workers должны использовать общее хранилище, если сессии разделяются; file требует общей файловой системы. Ограничьте доступ к backend и не логируйте содержимое сессий. + +## Совместимость и проверки + +`v2.0.0` требует Engine 9 и Server 7.1+ API; Engine 8 несовместим. При миграции проверьте cookie параметры и backend; формат данных старого хранилища может требовать отдельной миграции. `composer test` проверяет Engine bootstrap, Server handler contract, файловый round trip и безопасное восстановление без инстанцирования объектов. `composer test:mongo` — отдельный Mongo сценарий; обычный тест не запускает Redis/Mongo сервисы. + +## Практические руководства + +[Установка](/projects/triangle-session/install) · [Использование](/projects/triangle-session/usage) · [Эксплуатация](/projects/triangle-session/operations) · [Совместимость и тесты](/projects/triangle-session/compatibility). diff --git a/src/pages/projects/triangle-session/compatibility.mdx b/src/pages/projects/triangle-session/compatibility.mdx new file mode 100644 index 0000000..83cc667 --- /dev/null +++ b/src/pages/projects/triangle-session/compatibility.mdx @@ -0,0 +1,13 @@ +export const pageTitle = 'Совместимость и тесты Session' +export const description = 'Проверки handler contract, миграция и внешние сервисы.' + +# Совместимость и тесты Session + +Выпуск `v2.0.0` рассчитан на Engine 9 и Session API Server 7.1+; Engine 8 uses an incompatible earlier contract. При переходе проверьте cookie name/domain/path/SameSite/secure, выбранный handler и перенос существующих session данных. Не считайте старые файлы/ключи автоматически совместимыми. + +```sh +composer test +composer test:mongo +``` + +`composer test` проверяет Engine bootstrap, Server session-handler contracts, file-backed round trip и восстановление данных без выполнения object wakeup. `composer test:mongo` — отдельный сценарий; обычные проверки не поднимают Redis/Mongo сервисы. Проход теста файла не подтверждает сетевую доступность, ACL и поведение production backend. diff --git a/src/pages/projects/triangle-session/en.mdx b/src/pages/projects/triangle-session/en.mdx new file mode 100644 index 0000000..6e9d816 --- /dev/null +++ b/src/pages/projects/triangle-session/en.mdx @@ -0,0 +1,42 @@ +export const pageTitle = 'Triangle Session' +export const description = 'HTTP sessions for Triangle Engine using file, Redis, Redis Cluster, or MongoDB storage.' + +# Triangle Session + +Triangle Session connects Localzet Server HTTP sessions to Triangle Engine and provides the `session()` helper for the current request. Release [2.0.0](https://github.com/Triangle-org/Session/releases/tag/v2.0.0). + +Requirements: PHP `^8.1`, Engine `^9.0`; Engine 9 requires the Server 7.1+ session API. + +```sh +composer require triangle/session:^2.0 +composer show triangle/session +``` + +## Usage + +Engine loads `Triangle\Session\Bootstrap` automatically. If the application does not publish package config, `Triangle\Session\Install::install()` copies a missing template. + +```php +session(['user_id' => 42, 'preferences' => ['theme' => 'dark']]); +$userId = session('user_id'); +$theme = session('preferences.theme', 'light'); +$currentSession = session(); +``` + +Without arguments the helper returns the current request session; a string key reads and an array writes. Store scalars/arrays: objects from serialized storage are not instantiated. + +## Storage, cookies, and security + +Default `SESSION_TYPE=file` stores data under `runtime_path('sessions')`. Supported backends are `file`, `redis`, `redis_cluster`, and `mongo`; Redis needs ext-redis, Mongo needs `mongodb/mongodb` and ext-mongodb. Settings are under `session.config.`. + +Cookie defaults: `PHPSID`, HTTP-only enabled, secure disabled, empty domain and SameSite. For HTTPS set `SESSION_COOKIE_SECURE=true`; configure domain and SameSite for the actual origins and cross-site flow. `SESSION_LIFETIME` and `SESSION_COOKIE_LIFETIME` are independent settings. + +A session belongs to a request, not a worker process. Do not retain session objects in long-lived state. Multiple workers need shared storage when they must share sessions; file storage requires a shared filesystem. Restrict backend access and do not log session contents. + +## Compatibility and checks + +`v2.0.0` requires Engine 9 and the Server 7.1+ API; Engine 8 is incompatible. During migration, review cookie settings and backend; old stored data may need a separate migration. `composer test` checks Engine bootstrap, the Server handler contract, file round trips, and safe restoration without object instantiation. `composer test:mongo` is a separate Mongo scenario; regular tests do not start Redis/Mongo services. + +## Practical guides + +[Install](/projects/triangle-session/en/install) · [Usage](/projects/triangle-session/en/usage) · [Operations](/projects/triangle-session/en/operations) · [Compatibility and tests](/projects/triangle-session/en/compatibility). diff --git a/src/pages/projects/triangle-session/en/compatibility.mdx b/src/pages/projects/triangle-session/en/compatibility.mdx new file mode 100644 index 0000000..4d97701 --- /dev/null +++ b/src/pages/projects/triangle-session/en/compatibility.mdx @@ -0,0 +1,13 @@ +export const pageTitle = 'Session compatibility and tests' +export const description = 'Handler contract checks, migration, and external services.' + +# Session compatibility and tests + +Release `v2.0.0` targets Engine 9 and the Server 7.1+ session API; Engine 8 uses an incompatible earlier contract. During migration, check cookie name/domain/path/SameSite/secure, the selected handler, and whether existing session data needs migration. Do not assume old files/keys are automatically compatible. + +```sh +composer test +composer test:mongo +``` + +`composer test` checks Engine bootstrap, Server session-handler contracts, file-backed round trips, and restoration without object wakeups. `composer test:mongo` is separate; regular checks do not start Redis/Mongo services. A file test does not prove network access, ACLs, or production backend behavior. diff --git a/src/pages/projects/triangle-session/en/install.mdx b/src/pages/projects/triangle-session/en/install.mdx new file mode 100644 index 0000000..a7b7f09 --- /dev/null +++ b/src/pages/projects/triangle-session/en/install.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Install Triangle Session' +export const description = 'Requirements, Engine autoloading, and optional backend dependencies.' + +# Install Triangle Session + +Triangle Session 2.0.0 requires PHP `^8.1` and Triangle Engine `^9.0`; Engine 9 uses the Localzet Server 7.1+ session API. + +```sh +composer require triangle/session:^2.0 +composer show triangle/session triangle/engine localzet/server +``` + +Engine loads `Triangle\Session\Bootstrap` at startup. If the application does not publish package config, run `Triangle\Session\Install::install()` in the installation context. The default backend is file storage under `runtime_path('sessions')`; workers need write access to the directory. + +Optional backends: Redis/Redis Cluster require PHP ext-redis; Mongo requires `mongodb/mongodb` and ext-mongodb. Verify the selected extensions before configuring a driver and avoid installing optional integrations you do not need. diff --git a/src/pages/projects/triangle-session/en/operations.mdx b/src/pages/projects/triangle-session/en/operations.mdx new file mode 100644 index 0000000..ca08788 --- /dev/null +++ b/src/pages/projects/triangle-session/en/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'Session operations and security' +export const description = 'Configure backend/cookies and understand process-local boundaries.' + +# Session operations and security + +Supported `SESSION_TYPE` values are `file` (default), `redis`, `redis_cluster`, and `mongo`. Connection settings live under `session.config.`. Local files are not shared storage across workers on separate hosts; use Redis/Cluster/Mongo or a shared filesystem when supported by the deployment. + +Template cookie settings: name `PHPSID`, `http_only=true`, `secure=false`, empty domain and SameSite. Set `SESSION_COOKIE_SECURE=true` for HTTPS. Configure domain, path, and SameSite for actual origins and cross-site flows; avoid unnecessarily broad cookie scope. `SESSION_LIFETIME` and `SESSION_COOKIE_LIFETIME` are separate durations. + +Restrict access to session storage, do not log session values, and use trusted storage only. Do not retain request/session scope in long-lived worker state. diff --git a/src/pages/projects/triangle-session/en/usage.mdx b/src/pages/projects/triangle-session/en/usage.mdx new file mode 100644 index 0000000..c4e6c9a --- /dev/null +++ b/src/pages/projects/triangle-session/en/usage.mdx @@ -0,0 +1,17 @@ +export const pageTitle = 'Using a session' +export const description = 'Read and write values through the current HTTP request helper.' + +# Using a session + +The `session()` helper accesses the current request's session: + +```php +session(['user_id' => 42, 'preferences' => ['theme' => 'dark']]); +$userId = session('user_id'); +$theme = session('preferences.theme', 'light'); +$currentSession = session(); +``` + +Without arguments it returns the current session object; a string key reads a value and an array is passed to `put()`. Nested keys use dot notation. Store scalars and arrays: session handlers restore serialized values without instantiating arbitrary objects. + +Choose a backend with `SESSION_TYPE` and configure its `session.config.` section in `config/session.php`. Use shared storage when multiple workers must read/update the same user's session. diff --git a/src/pages/projects/triangle-session/install.mdx b/src/pages/projects/triangle-session/install.mdx new file mode 100644 index 0000000..a516ca4 --- /dev/null +++ b/src/pages/projects/triangle-session/install.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Установка Triangle Session' +export const description = 'Требования, автозагрузка Engine и доступные backend зависимости.' + +# Установка Triangle Session + +Triangle Session 2.0.0 требует PHP `^8.1` и Triangle Engine `^9.0`; Engine 9 использует Session API Localzet Server 7.1+. + +```sh +composer require triangle/session:^2.0 +composer show triangle/session triangle/engine localzet/server +``` + +Engine загружает `Triangle\Session\Bootstrap` при старте. Если приложение не публикует package config, выполните `Triangle\Session\Install::install()` в контексте установки. По умолчанию используется file backend с каталогом `runtime_path('sessions')`; каталогу нужны права записи для worker. + +Дополнительные backend: Redis/Redis Cluster требуют PHP ext-redis; Mongo требует `mongodb/mongodb` и ext-mongodb. Проверьте выбранные расширения перед конфигурацией и не устанавливайте необязательные driver-зависимости без необходимости. diff --git a/src/pages/projects/triangle-session/operations.mdx b/src/pages/projects/triangle-session/operations.mdx new file mode 100644 index 0000000..b0bc4b4 --- /dev/null +++ b/src/pages/projects/triangle-session/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'Сессии: эксплуатация и безопасность' +export const description = 'Настройка backend/cookie и process-local границы.' + +# Сессии: эксплуатация и безопасность + +Поддерживаемые `SESSION_TYPE`: `file` (default), `redis`, `redis_cluster`, `mongo`. Настройки подключения берутся из `session.config.`. Для нескольких workers на разных машинах локальные файлы не являются shared store; используйте Redis/Cluster/Mongo или общую файловую систему, если архитектура это поддерживает. + +Cookie параметры шаблона: имя `PHPSID`, `http_only=true`, `secure=false`, пустые domain и SameSite. Для HTTPS включите `SESSION_COOKIE_SECURE=true`. Установите domain, path и SameSite под origins и cross-site flow; не задавайте широкую область cookie без потребности. `SESSION_LIFETIME` и `SESSION_COOKIE_LIFETIME` задают разные сроки. + +Ограничьте доступ к session storage, не логируйте значения сессии, используйте только доверенное хранилище. Сессия и request scope не должны сохраняться в долгоживущем worker state. diff --git a/src/pages/projects/triangle-session/usage.mdx b/src/pages/projects/triangle-session/usage.mdx new file mode 100644 index 0000000..cf8f87f --- /dev/null +++ b/src/pages/projects/triangle-session/usage.mdx @@ -0,0 +1,17 @@ +export const pageTitle = 'Использование сессии' +export const description = 'Чтение и запись значений через helper текущего HTTP request.' + +# Использование сессии + +Helper `session()` обращается к session текущего request: + +```php +session(['user_id' => 42, 'preferences' => ['theme' => 'dark']]); +$userId = session('user_id'); +$theme = session('preferences.theme', 'light'); +$currentSession = session(); +``` + +Без аргумента helper возвращает объект текущей сессии; строковый ключ читает значение, массив передаёт значения в `put()`. Для вложенного ключа используется dot notation. Храните scalars и arrays: сессионные handlers восстанавливают сериализованные значения без инстанцирования произвольных объектов. + +Для выбора backend задайте `SESSION_TYPE` и параметры соответствующей секции `session.config.` в `config/session.php`. Выберите одно общее хранилище, если несколько workers должны читать и обновлять одну и ту же пользовательскую сессию. diff --git a/src/pages/projects/triangle-view.mdx b/src/pages/projects/triangle-view.mdx new file mode 100644 index 0000000..594526b --- /dev/null +++ b/src/pages/projects/triangle-view.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Triangle View 2.1.0 — шаблоны приложений' +export const description = 'Руководство Triangle View 2.1.0: установка, PHP-шаблоны, подключаемые адаптеры, конфигурация и безопасность вывода.' + +# Triangle View + +Triangle View связывает шаблоны PHP и опциональные движки Blade, Twig и ThinkPHP с ответом приложения Triangle Engine. + +**Версия:** 2.1.0 · **PHP:** 8.1+ · **Engine:** `^8.1 || ^9.0` · **Пакет:** `triangle/view`. + +- [Установка и первый ответ](triangle-view/install) +- [Рендеринг и передача данных](triangle-view/usage) +- [Настройка и безопасность шаблонов](triangle-view/operations) +- [Совместимость и тестирование](triangle-view/compatibility) + +По умолчанию используется `raw`: PHP-файлы `.phtml` включаются без автоматического HTML-экранирования. Значения, пришедшие от пользователя или из внешнего источника, необходимо экранировать в шаблоне. Переменные, переданные прямо в `view()`, имеют приоритет над переменными, ранее назначенными для текущего request. diff --git a/src/pages/projects/triangle-view/compatibility.mdx b/src/pages/projects/triangle-view/compatibility.mdx new file mode 100644 index 0000000..cb1a1a7 --- /dev/null +++ b/src/pages/projects/triangle-view/compatibility.mdx @@ -0,0 +1,30 @@ +export const pageTitle = 'Совместимость и тесты Triangle View' +export const description = 'Совместимость View 2.1.0, правила обновления, тест рендеринга и ограничения тестового покрытия.' + +# Совместимость и тесты + +## Поддерживаемые версии + +View 2.1.0 требует PHP `^8.1` и допускает `triangle/engine ^8.1 || ^9.0`. Engine 9 предназначен для Localzet Server 7; наличие Engine 8 в диапазоне сохраняет поддержку существующих приложений, но не означает совместимость с любыми другими major-версиями. + +```sh +composer require triangle/view:^2.1 +composer show triangle/view triangle/engine +``` + +## Обновление + +Сверьте lock-файл и конфигурацию `view.php`. Если приложение задаёт `VIEW_HANDLER`, установите соответствующий сторонний движок отдельно. Проверьте путь шаблонов и представления, которые используют `request`-assigned values: значения, явно переданные в helper, перекрывают назначенные ранее. + +Переход на `raw` может менять безопасность вывода: HTML не экранируется автоматически. Проверьте шаблоны с пользовательскими данными до публикации. + +## Проверки + +```sh +composer install +composer test +``` + +Тест `tests/engine_compatibility.php` проверяет совместимость с Engine и основной путь рендеринга. Он не проверяет все сторонние шаблонизаторы, HTML-контексты или шаблоны вашего приложения. Добавьте тесты на фактические страницы, особенно на вывод пользовательского текста. + +**Источники:** [релиз v2.1.0](https://github.com/Triangle-org/View/tree/v2.1.0), [Composer](https://github.com/Triangle-org/View/blob/v2.1.0/composer.json), [тест совместимости](https://github.com/Triangle-org/View/blob/v2.1.0/tests/engine_compatibility.php). diff --git a/src/pages/projects/triangle-view/en.mdx b/src/pages/projects/triangle-view/en.mdx new file mode 100644 index 0000000..222eeae --- /dev/null +++ b/src/pages/projects/triangle-view/en.mdx @@ -0,0 +1,15 @@ +export const pageTitle = 'Triangle View 2.1.0 — application templates' +export const description = 'Triangle View 2.1.0 guide: installation, PHP templates, optional adapters, configuration, and output safety.' + +# Triangle View + +Triangle View connects PHP templates and optional Blade, Twig, or ThinkPHP engines to responses in a Triangle Engine application. + +**Version:** 2.1.0 · **PHP:** 8.1+ · **Engine:** `^8.1 || ^9.0` · **Package:** `triangle/view`. + +- [Install and return a first response](triangle-view/en/install) +- [Render templates and pass data](triangle-view/en/usage) +- [Configure handlers and secure output](triangle-view/en/operations) +- [Compatibility and testing](triangle-view/en/compatibility) + +The default `raw` handler includes `.phtml` files as PHP and does not escape HTML automatically. Escape values from users or external sources in the template. Variables passed directly to `view()` take precedence over values previously assigned to the current request. diff --git a/src/pages/projects/triangle-view/en/compatibility.mdx b/src/pages/projects/triangle-view/en/compatibility.mdx new file mode 100644 index 0000000..a8d9395 --- /dev/null +++ b/src/pages/projects/triangle-view/en/compatibility.mdx @@ -0,0 +1,30 @@ +export const pageTitle = 'Triangle View compatibility and tests' +export const description = 'View 2.1.0 compatibility, upgrade notes, rendering checks, and test coverage limits.' + +# Compatibility and testing + +## Supported versions + +View 2.1.0 requires PHP `^8.1` and allows `triangle/engine ^8.1 || ^9.0`. Engine 9 targets Localzet Server 7; the Engine 8 range preserves compatibility for existing applications and does not imply support for other major versions. + +```sh +composer require triangle/view:^2.1 +composer show triangle/view triangle/engine +``` + +## Upgrade notes + +Review the lock file and `view.php` configuration. If the application sets `VIEW_HANDLER`, install the corresponding third-party template engine separately. Verify template paths and views that use request-assigned values: values explicitly passed to the helper override previous assignments. + +Switching to `raw` can affect output safety: HTML is not escaped automatically. Review templates that render user-provided values before deployment. + +## Checks + +```sh +composer install +composer test +``` + +The `tests/engine_compatibility.php` test checks Engine compatibility and the main rendering path. It does not cover every third-party engine, HTML context, or application template. Add tests for actual pages, especially those that render user-provided text. + +**Sources:** [v2.1.0 release](https://github.com/Triangle-org/View/tree/v2.1.0), [Composer manifest](https://github.com/Triangle-org/View/blob/v2.1.0/composer.json), [compatibility test](https://github.com/Triangle-org/View/blob/v2.1.0/tests/engine_compatibility.php). diff --git a/src/pages/projects/triangle-view/en/install.mdx b/src/pages/projects/triangle-view/en/install.mdx new file mode 100644 index 0000000..d760e08 --- /dev/null +++ b/src/pages/projects/triangle-view/en/install.mdx @@ -0,0 +1,37 @@ +export const pageTitle = 'Install Triangle View and return a first response' +export const description = 'PHP and Engine requirements, triangle/view installation, and a minimal phtml template example.' + +# Install and return a first response + +Requirements: PHP 8.1+, Composer, and Triangle Engine `^8.1 || ^9.0`. + +```sh +composer require triangle/view:^2.1 +``` + +Composer autoloads the package helper functions. The Engine installer copies the default `view.php` configuration only when the application does not already have one. + +Create `app//view/page.phtml` and call the helper from a request handler: + +```php + 'Catalog', 'items' => $items]); +``` + +```php +

+
    + +
  • + +
+``` + +Replace the application directory with the actual application name in your project. `view()` returns a `Triangle\Response` with status 200 by default. The example assumes `$items` was obtained and validated by the application. + +Verify the package: + +```sh +composer test +``` diff --git a/src/pages/projects/triangle-view/en/operations.mdx b/src/pages/projects/triangle-view/en/operations.mdx new file mode 100644 index 0000000..e6e692b --- /dev/null +++ b/src/pages/projects/triangle-view/en/operations.mdx @@ -0,0 +1,32 @@ +export const pageTitle = 'Triangle View configuration and security' +export const description = 'Configure view.handler and view.options, install optional template engines, escape output, and operate Triangle View.' + +# Configuration and security + +## Handler and options + +`config/view.php` selects `raw` by default. The `VIEW_HANDLER` environment variable can select `raw`, `blade`, `twig`, or `think`. Install third-party engines separately: `jenssegers/blade`, `twig/twig`, or `topthink/think-template`. Composer lists these as optional suggestions. + +Main options: + +```php +return [ + 'handler' => Triangle\View\Render\Raw::class, + 'options' => [ + 'view_suffix' => 'phtml', + 'vars' => [], + ], +]; +``` + +For applications and plugins, the handler is read from their Engine configuration namespace. If a configuration file already exists, the installer does not overwrite it; update settings explicitly. + +## Escaping and trust + +Raw templates execute as PHP and do not escape output automatically. For HTML text and attribute contexts, escape untrusted strings with `htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')`. JavaScript, URL, and CSS contexts have different encoding rules; HTML escaping alone is not suitable for every context. + +Do not use user input as a template name or PHP code. Template access is part of the application's trust boundary. Avoid passing secrets to templates unless required, because templates can expose them in the response. + +## Limits + +View creates a response body and status; it does not replace controllers, authorization, CSRF protection, or application caching rules. Template paths and optional engines depend on each project's configuration. diff --git a/src/pages/projects/triangle-view/en/usage.mdx b/src/pages/projects/triangle-view/en/usage.mdx new file mode 100644 index 0000000..50a4b31 --- /dev/null +++ b/src/pages/projects/triangle-view/en/usage.mdx @@ -0,0 +1,29 @@ +export const pageTitle = 'Triangle View rendering and data' +export const description = 'View helpers, template paths, and precedence of variables passed to a template.' + +# Render templates and pass data + +## `view()` and templates + +```php +return view('catalog/show', ['product' => $product], app: 'shop'); +``` + +`view($template = null, array $vars = [], ?string $app = null, ?string $plugin = null, int $http_code = 200)` selects the configured handler and returns a `Triangle\Response`. When the template is `null`, it is derived from the current request controller/action. The base path for the `shop` application is `app/shop/view/...`; the default suffix is `.phtml`. + +For explicit adapter selection, the package provides `raw_view()`, `blade_view()`, `twig_view()`, and `think_view()`. Helpers for optional engines require the corresponding Composer package. + +## Template data + +`view()` combines current request-assigned variables with the provided array; explicitly provided values take precedence. You can assign a value separately: + +```php +Triangle\View\Support\View::assign('section', 'billing'); +return view('account', ['section' => 'profile']); // explicit value wins +``` + +`View::vars()` returns request-assigned variables. `View::assign($array, merge_recursive: true)` enables recursive merging for nested arrays; without that flag, assignment uses ordinary `array_merge`. + +## Composed templates + +The raw renderer supports pre-render and post-render templates through `view.options.pre_renders` and `view.options.post_renders`. Use them for shared layouts only after testing the rendered order and data structure in the application. diff --git a/src/pages/projects/triangle-view/install.mdx b/src/pages/projects/triangle-view/install.mdx new file mode 100644 index 0000000..27db1dd --- /dev/null +++ b/src/pages/projects/triangle-view/install.mdx @@ -0,0 +1,38 @@ +export const pageTitle = 'Установка и первый ответ Triangle View' +export const description = 'Требования PHP и Engine, установка triangle/view и минимальный пример шаблона phtml.' + +# Установка и первый ответ + +Требуются PHP 8.1+, Composer и Triangle Engine `^8.1 || ^9.0`. + +```sh +composer require triangle/view:^2.1 +``` + +Пакет регистрирует helper-функции через Composer autoload. Установщик Engine копирует стандартный `view.php` в конфигурацию, только если такого файла ещё нет. + +Создайте шаблон `app/<имя-приложения>/view/page.phtml` и вызовите helper из обработчика Engine: + +```php + 'Каталог', 'items' => $items]); +``` + +```php + +

+
    + +
  • + +
+``` + +Замените `app/shop` на реальное имя приложения в проекте. `view()` возвращает `Triangle\Response` со статусом по умолчанию 200. В примере предполагается, что `$items` получен и валидирован приложением. + +Проверка пакета: + +```sh +composer test +``` diff --git a/src/pages/projects/triangle-view/operations.mdx b/src/pages/projects/triangle-view/operations.mdx new file mode 100644 index 0000000..00ebb0e --- /dev/null +++ b/src/pages/projects/triangle-view/operations.mdx @@ -0,0 +1,32 @@ +export const pageTitle = 'Конфигурация и безопасность Triangle View' +export const description = 'Настройка view.handler и view.options, дополнительные шаблонизаторы, экранирование и эксплуатация Triangle View.' + +# Конфигурация и безопасность + +## Handler и параметры + +`config/view.php` по умолчанию выбирает `raw`. Переменная окружения `VIEW_HANDLER` может выбрать `raw`, `blade`, `twig` или `think`. Сторонний движок устанавливается отдельно: `jenssegers/blade`, `twig/twig` либо `topthink/think-template`. Пакет помечает эти зависимости как optional suggestions. + +Основные параметры: + +```php +return [ + 'handler' => Triangle\View\Render\Raw::class, + 'options' => [ + 'view_suffix' => 'phtml', + 'vars' => [], + ], +]; +``` + +Для приложений и плагинов Engine handler читается из их конфигурационного namespace. Если конфиг уже существует, install helper не перезаписывает его; обновление настроек выполняйте явно. + +## Экранирование и доверие + +Raw templates исполняются как PHP-код и не экранируют вывод автоматически. Для HTML-контекста экранируйте недоверенные строки через `htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')`. Для JavaScript, URL и CSS нужны правила экранирования соответствующего контекста; HTML-экранирования недостаточно для всех контекстов. + +Не используйте содержимое пользовательского ввода как имя шаблона или PHP-код. Доступ к шаблонам — часть границы доверия приложения. Не размещайте секреты как переменные представления без необходимости: шаблон может вывести их в ответ. + +## Ограничения + +View формирует тело и статус ответа, но не заменяет контроллер, авторизацию, CSRF-защиту или правила кэширования приложения. Путь шаблона и необязательные движки зависят от конфигурации конкретного проекта. diff --git a/src/pages/projects/triangle-view/usage.mdx b/src/pages/projects/triangle-view/usage.mdx new file mode 100644 index 0000000..8fac2d8 --- /dev/null +++ b/src/pages/projects/triangle-view/usage.mdx @@ -0,0 +1,29 @@ +export const pageTitle = 'Рендеринг и данные Triangle View' +export const description = 'Функции view и специализированные render helpers, пути шаблонов и приоритет переменных.' + +# Рендеринг и передача данных + +## `view()` и шаблоны + +```php +return view('catalog/show', ['product' => $product], app: 'web'); +``` + +Функция `view($template = null, array $vars = [], ?string $app = null, ?string $plugin = null, int $http_code = 200)` выбирает handler из конфигурации и возвращает `Triangle\Response`. При `null` имя шаблона выводится из controller/action текущего request. Для шаблона приложения `web` базовый путь имеет вид `app/web/view/...`; расширение по умолчанию — `.phtml`. + +Для явного выбора адаптера пакет предоставляет `raw_view()`, `blade_view()`, `twig_view()` и `think_view()`. Функции для необязательных движков требуют соответствующий пакет Composer. + +## Данные шаблона + +`view()` объединяет переменные из текущего request с переданным массивом; явно переданный массив имеет приоритет. Можно назначать значения отдельно: + +```php +Triangle\View\Support\View::assign('section', 'billing'); +return view('account', ['section' => 'profile']); // явное значение profile выигрывает +``` + +`View::vars()` возвращает назначенные request-переменные. Для вложенных массивов `View::assign($array, merge_recursive: true)` включает рекурсивное объединение; без этого флага назначение выполняет обычный `array_merge`. + +## Составные шаблоны + +Raw renderer поддерживает pre-render и post-render шаблоны из параметров конфигурации `view.options.pre_renders` и `view.options.post_renders`. Используйте их для общего layout только после проверки фактического порядка вывода и структуры данных в тесте приложения. diff --git a/src/pages/projects/triangle-web.mdx b/src/pages/projects/triangle-web.mdx new file mode 100644 index 0000000..68a84fe --- /dev/null +++ b/src/pages/projects/triangle-web.mdx @@ -0,0 +1,47 @@ +export const pageTitle = 'Triangle Web' +export const description = 'MVC-шаблон Triangle на базе Engine, HTTP-компонента, маршрутизации и представлений.' + +# Triangle Web + +Triangle Web — приложение-шаблон с MVC-структурой на Triangle Engine и Triangle HTTP. Опубликованный выпуск — [`v8.0.1`](https://github.com/Triangle-org/Web/releases/tag/v8.0.1). Тип Composer — `project`; в опубликованном манифесте PHP `^8.2`, `ext-curl`, `ext-json`, Engine `^8.1`, Engine HTTP `^2.0`, Console `^1.3`, Database `^1.0`, Session `^1.0`, View `^2.0`, Events `^1.0`. Текущий checkout `dc1335b1` — четыре коммита после тега; manifest сохраняет эти constraints, а preview lock и CI относятся к текущему checkout. + +```sh +composer create-project triangle/web:^8.0 my-web-app +cd my-web-app +composer show triangle/engine triangle/engine-http triangle/web +``` + +## Первые маршруты и контроллер + +Точка входа `master` загружает Composer autoload, задаёт пути, загружает `.env`, вызывает Engine autoloader и запускает Console. Серверные параметры задаются в `config/server.php`; исходный шаблон слушает `http://127.0.0.1:8000`, число workers по умолчанию равно `cpu_count() * 4`. + +В `config/route.php` маршрут регистрируется через Router: + +```php +use Triangle\Request; +use Triangle\Response; +use Triangle\Router; + +Router::any('/hello/{name}', function (Request $request, string $name): Response { + return response("Привет, $name!"); +}); +``` + +В шаблоне `app/controller/Index.php` показаны методы, возвращающие `response(...)`, `responseJson(...)` и `view('index/view', [...])`. Views настраиваются в `config/view.php`; renderer выбирается через `VIEW_HANDLER` (`raw` по умолчанию, также перечислены blade/think/twig). Пример HTTP запуска — `php master start`; фактические CLI команды сверяйте с установленным Triangle Console. + +## Конфигурация и эксплуатация + +Шаблон включает `config/` для server, routes, middleware, database, session, view, logging, events и других интеграций. Каталог `public` предназначен для публичных файлов, `runtime` — для служебных файлов по конфигурации проекта. Изменяйте только нужные параметры и храните секреты в окружении, а не в tracked config. + +В исходном `config/app.php` включён `debug=true`, а CORS заголовки заданы широко: origin `*`, credentials `true`, методы/headers `*`. Перед production явно задайте debug=false и согласуйте origin, credentials, методы и заголовки с доверенными клиентами. Не полагайтесь на эти значения как на безопасную политику. Ограничьте bind address и сетевой доступ; default loopback слушатель не делает сервис публичным. + +## Совместимость и проверки + +Release `v8.0.1` ограничивает Engine до `^8.1` и включает компоненты соответствующих major-линий; это не установка на Engine 9. Проверьте совместимость проекта перед совместным обновлением Triangle компонентов. `composer.json` не объявляет lint/test scripts, поэтому для этого checkout нет заявленной пакетной команды автотестов. HTTP smoke/integration checks должны выполняться в приложении с установленными версиями зависимостей. Текущий README содержит только badges; описание на этой странице сверено с entry point, конфигурацией, контроллером и маршрутом. + +## Практические руководства + +- [Создание приложения и запуск](triangle-web/install) +- [Маршруты, контроллеры и ответы](triangle-web/usage) +- [Конфигурация и production-подготовка](triangle-web/operations) +- [Релиз, preview, обновление и проверки](triangle-web/compatibility) diff --git a/src/pages/projects/triangle-web/compatibility.mdx b/src/pages/projects/triangle-web/compatibility.mdx new file mode 100644 index 0000000..f138122 --- /dev/null +++ b/src/pages/projects/triangle-web/compatibility.mdx @@ -0,0 +1,13 @@ +export const pageTitle = 'Совместимость и проверки Web' +export const description = 'Engine 8.1 требования и границы доступных package tests.' + +# Совместимость и проверки Web + +Тег `v8.0.1` и текущий checkout Web требуют Engine `^8.1` и перечисленные компоненты своих поддерживаемых major линий. Composer constraint `^8.1` не включает Engine 9. До обновления компонента сравните его constraints с `composer.json` приложения и проверьте lock. + +```sh +composer validate --strict --no-check-publish +composer show triangle/web triangle/engine triangle/engine-http +``` + +Манифест не объявляет `test` или `lint` scripts; отдельного test suite в checkout нет. Эти команды проверяют метаданные/разрешение, но не HTTP поведение. Добавьте integration checks для маршрутов, статических файлов, middleware, views, sessions и ошибочных запросов. Текущий README содержит только badges; факты страницы взяты из `master`, config и example controller/route. diff --git a/src/pages/projects/triangle-web/en.mdx b/src/pages/projects/triangle-web/en.mdx new file mode 100644 index 0000000..d089a9a --- /dev/null +++ b/src/pages/projects/triangle-web/en.mdx @@ -0,0 +1,47 @@ +export const pageTitle = 'Triangle Web' +export const description = 'MVC project template built on Triangle Engine, HTTP integration, routing, and views.' + +# Triangle Web + +Triangle Web is an MVC project template built on Triangle Engine and Triangle HTTP. Published release: [`v8.0.1`](https://github.com/Triangle-org/Web/releases/tag/v8.0.1). Composer type is `project`; the published manifest requires PHP `^8.2`, `ext-curl`, `ext-json`, Engine `^8.1`, Engine HTTP `^2.0`, Console `^1.3`, Database `^1.0`, Session `^1.0`, View `^2.0`, and Events `^1.0`. The current checkout at `dc1335b1` is four commits beyond the tag; it retains these constraints, while its preview lock file and CI belong to this checkout. + +```sh +composer create-project triangle/web:^8.0 my-web-app +cd my-web-app +composer show triangle/engine triangle/engine-http triangle/web +``` + +## First route and controller + +The `master` entry point loads Composer autoloading, sets paths, loads `.env`, starts the Engine autoloader, and runs Console. Server settings are in `config/server.php`; the template listens on `http://127.0.0.1:8000` and defaults to `cpu_count() * 4` workers. + +Register a route in `config/route.php`: + +```php +use Triangle\Request; +use Triangle\Response; +use Triangle\Router; + +Router::any('/hello/{name}', function (Request $request, string $name): Response { + return response("Hello, $name!"); +}); +``` + +The template's `app/controller/Index.php` shows handlers returning `response(...)`, `responseJson(...)`, and `view('index/view', [...])`. Views are configured in `config/view.php`; `VIEW_HANDLER` selects the renderer (`raw` by default; blade/think/twig are also listed). A typical HTTP startup is `php master start`; check commands against the installed Triangle Console version. + +## Configuration and operations + +The template includes config for server, routes, middleware, database, session, views, logging, events, and other integrations. `public` is for public assets and `runtime` for runtime files as configured by the project. Change only required settings and keep credentials in the environment rather than tracked config. + +The source `config/app.php` sets `debug=true` and broad CORS headers: origin `*`, credentials `true`, and wildcard methods/headers. Before production, explicitly set debug=false and choose allowed origins, credentials, methods, and headers for trusted clients. Do not treat these defaults as a security policy. Restrict the bind address and network access; the default loopback listener is not public exposure. + +## Compatibility and checks + +Release `v8.0.1` constrains Engine to `^8.1` and uses components from the corresponding major lines; it is not an Engine 9 installation. Verify compatibility before updating Triangle components together. `composer.json` declares no lint/test scripts, so this checkout has no package-provided automated test command. Run HTTP smoke/integration checks in the application with its resolved dependencies. The current README contains badges only; this page is based on the entry point, config, controller, and route source. + +## Practical guides + +- [Create and start an application](triangle-web/en/install) +- [Routes, controllers, and responses](triangle-web/en/usage) +- [Configuration and production preparation](triangle-web/en/operations) +- [Release, preview, upgrades, and checks](triangle-web/en/compatibility) diff --git a/src/pages/projects/triangle-web/en/compatibility.mdx b/src/pages/projects/triangle-web/en/compatibility.mdx new file mode 100644 index 0000000..bddaeb8 --- /dev/null +++ b/src/pages/projects/triangle-web/en/compatibility.mdx @@ -0,0 +1,13 @@ +export const pageTitle = 'Web compatibility and checks' +export const description = 'Engine 8.1 constraints and the limits of package test coverage.' + +# Web compatibility and checks + +Tag `v8.0.1` and the current Web checkout require Engine `^8.1` and the listed component major lines. Composer constraint `^8.1` does not include Engine 9. Before updating a component, compare its constraints with the application `composer.json` and inspect the lock file. + +```sh +composer validate --strict --no-check-publish +composer show triangle/web triangle/engine triangle/engine-http +``` + +The manifest declares no `test` or `lint` scripts, and the checkout has no test suite. These commands validate metadata/resolution, not HTTP behavior. Add integration checks for routes, static files, middleware, views, sessions, and invalid requests. The current README contains badges only; page facts come from `master`, config, and example controller/route. diff --git a/src/pages/projects/triangle-web/en/install.mdx b/src/pages/projects/triangle-web/en/install.mdx new file mode 100644 index 0000000..1c517fa --- /dev/null +++ b/src/pages/projects/triangle-web/en/install.mdx @@ -0,0 +1,14 @@ +export const pageTitle = 'Install Triangle Web' +export const description = 'Create a Triangle Engine 8.1 project and inspect its dependencies.' + +# Install Triangle Web + +Triangle Web is published as Composer project `v8.0.1`. Its release requirements are PHP `^8.2`, `ext-curl`, `ext-json`, Engine `^8.1`, Engine HTTP `^2.0`, Console `^1.3`, Database `^1.0`, Session `^1.0`, View `^2.0`, and Events `^1.0`. + +```sh +composer create-project triangle/web:^8.0 my-web-app +cd my-web-app +composer show triangle/web triangle/engine triangle/engine-http triangle/console triangle/database triangle/session triangle/view triangle/events +``` + +Check `composer.lock` and PHP extensions. Engine constraint `^8.1` excludes Engine 9. The project entry point is `master`: it loads autoloading, sets paths, reads `.env`, starts the Engine autoloader, and runs Console. Prepare environment-specific `.env`, `public`, and `runtime` paths before startup; do not commit secrets. diff --git a/src/pages/projects/triangle-web/en/operations.mdx b/src/pages/projects/triangle-web/en/operations.mdx new file mode 100644 index 0000000..b16534b --- /dev/null +++ b/src/pages/projects/triangle-web/en/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'Web configuration and operations' +export const description = 'Set safe CORS/debug values, listener, and worker count.' + +# Web configuration and operations + +`config/server.php` defines `listen`, `count`, handler, paths, and logs. The template listens on loopback `http://127.0.0.1:8000` and defaults workers to `cpu_count() * 4`. Size concurrency for the application and use a configured TLS reverse proxy when external access is needed. + +The template `config/app.php` sets `debug=true` and broad CORS values: `Access-Control-Allow-Origin: *`, credentials `true`, and wildcard methods/headers. Disable debug before production and specify exact origins, methods, headers, and credential policy; do not deploy sample settings without review. + +Keep secrets out of tracked config and protect `.env`, runtime, and logs. Check write permissions, database/session availability, body/package size limits, and upstream timeouts. `composer.json` declares no operational health checks or test scripts; add application-level checks. diff --git a/src/pages/projects/triangle-web/en/usage.mdx b/src/pages/projects/triangle-web/en/usage.mdx new file mode 100644 index 0000000..6270993 --- /dev/null +++ b/src/pages/projects/triangle-web/en/usage.mdx @@ -0,0 +1,20 @@ +export const pageTitle = 'Web routes and controllers' +export const description = 'Add a route and inspect HTML, JSON, and view handlers.' + +# Web routes and controllers + +`config/route.php` registers routes through `Triangle\Router`: + +```php +use Triangle\Request; +use Triangle\Response; +use Triangle\Router; + +Router::any('/hello/{name}', function (Request $request, string $name): Response { + return response("Hello, $name!"); +}); +``` + +`Router::any` handles any HTTP method for that route. Template `app/controller/Index.php` demonstrates `response(...)`, `responseJson('ok')`, and `view('index/view', ['name' => 'Triangle'])`. `config/view.php` selects a renderer with `VIEW_HANDLER`; the default is `raw`, and template options include `blade`, `think`, and `twig`. + +After `php master start`, check the endpoint from `config/server.php` (default `http://127.0.0.1:8000`). For this example, request `/hello/Ada`. Inspect available commands with `php master list` for the Console version actually resolved. diff --git a/src/pages/projects/triangle-web/install.mdx b/src/pages/projects/triangle-web/install.mdx new file mode 100644 index 0000000..22c7b4d --- /dev/null +++ b/src/pages/projects/triangle-web/install.mdx @@ -0,0 +1,14 @@ +export const pageTitle = 'Установка Triangle Web' +export const description = 'Создайте проект на Triangle Engine 8.1 и проверьте зависимости.' + +# Установка Triangle Web + +Triangle Web опубликован как Composer project `v8.0.1`. Requirements этого релиза: PHP `^8.2`, `ext-curl`, `ext-json`, Engine `^8.1`, Engine HTTP `^2.0`, Console `^1.3`, Database `^1.0`, Session `^1.0`, View `^2.0`, Events `^1.0`. + +```sh +composer create-project triangle/web:^8.0 my-web-app +cd my-web-app +composer show triangle/web triangle/engine triangle/engine-http triangle/console triangle/database triangle/session triangle/view triangle/events +``` + +Проверьте `composer.lock` и PHP extensions. Ограничение Engine `^8.1` не принимает Engine 9. Точка входа проекта — `master`: она загружает autoload, задаёт пути, читает `.env`, запускает Engine autoloader и Console. Перед запуском подготовьте рабочие `.env`, каталоги `public` и `runtime`; не храните секреты в git. diff --git a/src/pages/projects/triangle-web/operations.mdx b/src/pages/projects/triangle-web/operations.mdx new file mode 100644 index 0000000..0662741 --- /dev/null +++ b/src/pages/projects/triangle-web/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'Настройка и эксплуатация Web' +export const description = 'Безопасные значения CORS/debug, listener и worker count.' + +# Настройка и эксплуатация Web + +В `config/server.php` находятся `listen`, `count`, handler, пути и логи. Исходный шаблон слушает loopback `http://127.0.0.1:8000`, а число workers по умолчанию — `cpu_count() * 4`. Подбирайте concurrency под приложение и развертывайте за настроенным TLS reverse proxy, если нужен внешний доступ. + +В `config/app.php` шаблон включает `debug=true` и широкие CORS значения: `Access-Control-Allow-Origin: *`, credentials `true`, методы/headers `*`. До production отключите debug и задайте точные origins, методы, headers и credentials; не используйте sample-настройки без пересмотра. + +Секреты храните вне tracked config, защитите `.env`, runtime и логи. Проверьте права записи, доступность database/session storage, ограничения body/package sizes и upstream timeouts. `composer.json` не задаёт операционных health checks или test scripts — добавьте проверки на уровне приложения. diff --git a/src/pages/projects/triangle-web/usage.mdx b/src/pages/projects/triangle-web/usage.mdx new file mode 100644 index 0000000..75b6c9f --- /dev/null +++ b/src/pages/projects/triangle-web/usage.mdx @@ -0,0 +1,20 @@ +export const pageTitle = 'Маршруты и контроллеры Web' +export const description = 'Добавьте маршрут и проверьте HTML, JSON и view handlers.' + +# Маршруты и контроллеры Web + +Файл `config/route.php` регистрирует маршруты через `Triangle\Router`: + +```php +use Triangle\Request; +use Triangle\Response; +use Triangle\Router; + +Router::any('/hello/{name}', function (Request $request, string $name): Response { + return response("Привет, $name!"); +}); +``` + +`Router::any` обрабатывает любой HTTP method для route. Шаблон `app/controller/Index.php` показывает `response(...)`, `responseJson('ok')` и `view('index/view', ['name' => 'Triangle'])`. `config/view.php` выбирает renderer через `VIEW_HANDLER`; значение по умолчанию `raw`, варианты шаблона — `blade`, `think`, `twig`. + +После запуска `php master start` проверьте endpoint по адресу из `config/server.php` (по умолчанию `http://127.0.0.1:8000`). Для примера выше запросите `/hello/Ada`. Команды CLI сверяйте через `php master list` для реально разрешённой версии Console. diff --git a/src/pages/projects/triangle-ws.mdx b/src/pages/projects/triangle-ws.mdx new file mode 100644 index 0000000..1d243d2 --- /dev/null +++ b/src/pages/projects/triangle-ws.mdx @@ -0,0 +1,34 @@ +export const pageTitle = 'Triangle WS' +export const description = 'Экспериментальный WebSocket-first шаблон Triangle с маршрутами, callback API и локальными рассылками.' + +# Triangle WS + +Triangle WS — экспериментальный WebSocket-first шаблон приложения на Triangle Engine и Server. Выпущен тег [`v1.0.4`](https://github.com/Triangle-org/WS/releases/tag/v1.0.4). Опубликованный Composer manifest требует PHP `^8.2`, Engine `^8.1` и Engine WS `^2.0`, но Engine WS 2.0.0 требует Engine `^9.0`; эти ограничения несовместимы. Не рассчитывайте на успешную установку `v1.0.4`, пока manifest не исправлен. Текущий checkout отличается: он требует Engine WS `^1.1` и lock разрешает Engine 8.1.11 / Engine WS 1.1.1. Сверяйте метаданные выбранного релиза и исходной ветки отдельно. + +## Маршруты и payload + +Шаблон запускает Engine через `master`, загружает autoload и `config/route.php`. WebSocket callback роутера получает текущий payload как строку (во время handshake значение может быть `null`); ответ можно вернуть через `response()`: + +```php +use Triangle\Router; + +Router::any('/chat', static function (?string $payload) { + return response($payload ?? 'connected'); +}); +``` + +Шаблон `config/server.php` задаёт `websocket://0.0.0.0:8080`, handler `Triangle\Ws\App`, лимит пакета 10 MiB и один worker. В исходном README особо отмечено, что текущая конфигурация рассчитана на один процесс. Проверьте TLS termination, bind address, ограничения сообщения и сетевой ACL в своей среде. + +`Triangle\Ws\App::sendToAll($data, $excludeCurrent)` отправляет соединениям серверов текущего процесса. `sendToGroup(...)` в текущей реализации выбирает соединения по пути WebSocket-запроса; это path scope, а не произвольная именованная группа. Эти методы не дают межпроцессной рассылки или общего состояния. Для нескольких процессов/узлов нужен отдельный broker/shared-state слой. + +## Ограничения и проверки + +Шаблон экспериментальный и не заменяет зрелую HTTP app без оценки сценария. Поддерживайте callbacks неблокирующими; проверьте handshake, маршрутизацию, disconnect, ошибочный/крупный payload и восстановление соединения в собственных integration tests. Текущий `composer.json` не объявляет test/lint scripts. Компонент публикует только однопроцессную модель рассылки из README; delivery guarantees, durable messages и cluster coordination не заявлены. + + +## Практические руководства + +- [Установка и статус зависимостей](triangle-ws/install) +- [Маршруты и payload](triangle-ws/usage) +- [Эксплуатация и ограничения](triangle-ws/operations) +- [Совместимость и проверки](triangle-ws/compatibility) diff --git a/src/pages/projects/triangle-ws/compatibility.mdx b/src/pages/projects/triangle-ws/compatibility.mdx new file mode 100644 index 0000000..ace059d --- /dev/null +++ b/src/pages/projects/triangle-ws/compatibility.mdx @@ -0,0 +1,8 @@ +export const pageTitle = 'Совместимость и проверка WS' +export const description = 'Сравните constraints v1.0.4 с разрешённой связкой checkout.' + +# Совместимость и проверка WS + +Опубликованный `v1.0.4` требует Engine `^8.1` + Engine WS `^2.0`, а Engine WS 2.0.0 требует Engine `^9.0`; эти ranges несовместимы. Текущий checkout переходит на Engine WS `^1.1` и имеет lock с Engine 8.1.11 / Engine WS 1.1.1. Это различие нужно разрешить до использования опубликованного пакета. + +`composer.json` не объявляет test/lint scripts, автоматизированного package test suite нет. Проверяйте выбранный checkout фактическим приложением: Composer resolution, handshake, callback route, message response, malformed/oversized frames, disconnect/reconnect, authentication и graceful stop. Локальный успешный запуск на одной машине не подтверждает multi-process delivery: send helpers остаются process-local. diff --git a/src/pages/projects/triangle-ws/en.mdx b/src/pages/projects/triangle-ws/en.mdx new file mode 100644 index 0000000..78ce46e --- /dev/null +++ b/src/pages/projects/triangle-ws/en.mdx @@ -0,0 +1,34 @@ +export const pageTitle = 'Triangle WS' +export const description = 'Experimental WebSocket-first Triangle template with routing, callbacks, and process-local broadcasts.' + +# Triangle WS + +Triangle WS is an experimental WebSocket-first application template built on Triangle Engine and Server. Published tag: [`v1.0.4`](https://github.com/Triangle-org/WS/releases/tag/v1.0.4). The published Composer manifest requires PHP `^8.2`, Engine `^8.1`, and Engine WS `^2.0`, but Engine WS 2.0.0 requires Engine `^9.0`; these constraints conflict. Do not expect `v1.0.4` installation to succeed until the manifest is corrected. The current checkout differs: it requires Engine WS `^1.1` and its lock resolves Engine 8.1.11 / Engine WS 1.1.1. Check release metadata separately from the source branch. + +## Routes and payloads + +The template starts Engine through `master`, loads autoloading, and reads `config/route.php`. A WebSocket router callback receives the current payload as a string (during handshake it may be `null`); return a response with `response()`: + +```php +use Triangle\Router; + +Router::any('/chat', static function (?string $payload) { + return response($payload ?? 'connected'); +}); +``` + +The source `config/server.php` sets `websocket://0.0.0.0:8080`, handler `Triangle\Ws\App`, a 10 MiB package limit, and one worker. The project README describes the current config as a one-process setup. Review TLS termination, bind address, message size, and network ACLs for your environment. + +`Triangle\Ws\App::sendToAll($data, $excludeCurrent)` sends to connections on servers in the current process. `sendToGroup(...)` currently selects connections by the WebSocket request path; it is a path scope, not an arbitrary named group. These methods do not provide cross-process broadcast or shared state. Multi-process/node deployments need a separate broker/shared-state layer. + +## Limits and checks + +The template is experimental; evaluate the use case before replacing a mature HTTP application. Keep callbacks non-blocking and add application integration tests for handshake, routing, disconnect, invalid/large payloads, and reconnect behavior. The current `composer.json` declares no test/lint scripts. The documented broadcast model is process-local; delivery guarantees, durable messages, and cluster coordination are not provided. + + +## Practical guides + +- [Install and dependency status](triangle-ws/en/install) +- [Routes and payloads](triangle-ws/en/usage) +- [Operations and limits](triangle-ws/en/operations) +- [Compatibility and checks](triangle-ws/en/compatibility) diff --git a/src/pages/projects/triangle-ws/en/compatibility.mdx b/src/pages/projects/triangle-ws/en/compatibility.mdx new file mode 100644 index 0000000..6138175 --- /dev/null +++ b/src/pages/projects/triangle-ws/en/compatibility.mdx @@ -0,0 +1,8 @@ +export const pageTitle = 'WS compatibility and verification' +export const description = "Compare v1.0.4 constraints with the checkout's resolved dependency set." + +# WS compatibility and verification + +Published `v1.0.4` requires Engine `^8.1` plus Engine WS `^2.0`, while Engine WS 2.0.0 requires Engine `^9.0`; these ranges conflict. The current checkout switches to Engine WS `^1.1` and locks Engine 8.1.11 / Engine WS 1.1.1. Resolve this discrepancy before using the published package. + +`composer.json` declares no test/lint scripts and the project has no package test suite. Verify the selected checkout in the real application: dependency resolution, handshake, callback routing, message responses, malformed/oversized frames, disconnect/reconnect, authentication, and graceful stop. A successful local run on one machine does not prove multi-process delivery; the send helpers remain process-local. diff --git a/src/pages/projects/triangle-ws/en/install.mdx b/src/pages/projects/triangle-ws/en/install.mdx new file mode 100644 index 0000000..2136ef1 --- /dev/null +++ b/src/pages/projects/triangle-ws/en/install.mdx @@ -0,0 +1,14 @@ +export const pageTitle = 'Install Triangle WS' +export const description = 'Differences between the published Composer manifest and the current checkout.' + +# Install Triangle WS + +`triangle/ws` is published as project tag `v1.0.4`. Its tagged manifest requires PHP `^8.2`, `triangle/engine:^8.1`, and `triangle/engine-ws:^2.0`. However, `triangle/engine-ws` v2.0.0 itself requires Engine `^9.0`; Engine `^8.1` and that dependency cannot be satisfied together. The published WS manifest therefore has no resolvable dependency set for this combination. Do not expect `composer create-project` to succeed until the release constraints are corrected. + +The current checkout differs: its `composer.json` uses `triangle/engine-ws:^1.1`; its lock contains Engine 8.1.11 and Engine WS 1.1.1. That is the source checkout's state, not the v1.0.4 tag manifest. + +```sh +composer show triangle/ws triangle/engine triangle/engine-ws +``` + +Check the release manifest and lock file for the selected commit before use. Do not deploy the current preview combination merely because its local lock resolves. diff --git a/src/pages/projects/triangle-ws/en/operations.mdx b/src/pages/projects/triangle-ws/en/operations.mdx new file mode 100644 index 0000000..8254125 --- /dev/null +++ b/src/pages/projects/triangle-ws/en/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'WS operations and limits' +export const description = 'Single worker, in-process broadcast, and network boundaries.' + +# WS operations and limits + +The current checkout configures `websocket://0.0.0.0:8080`, `Triangle\Ws\App`, `count = 1`, and `max_package_size = 10 * 1024 * 1024`. The README describes the template as an experimental, single-process WebSocket-first project. Restrict the port with a firewall/TLS proxy, enforce message-size expectations, and implement application authentication/origin policy. + +`sendToAll()` sends to connections on servers in the current process. `sendToGroup()` uses the current WebSocket request path as its scope; it is not an arbitrary named group. Neither method coordinates broadcasts across processes/nodes or provides shared state. Horizontal scaling needs an external broker/shared-state and routing layer. + +Callbacks run in an event-loop context: avoid long blocking network/CPU work. Durable message delivery, retries, replay, and exactly-once behavior are not provided. diff --git a/src/pages/projects/triangle-ws/en/usage.mdx b/src/pages/projects/triangle-ws/en/usage.mdx new file mode 100644 index 0000000..b8a2dd0 --- /dev/null +++ b/src/pages/projects/triangle-ws/en/usage.mdx @@ -0,0 +1,18 @@ +export const pageTitle = 'Routes and WebSocket payloads' +export const description = 'Exercise route callbacks against the current checkout source.' + +# Routes and WebSocket payloads + +In the current checkout, `master` loads Engine, then routes are registered in `config/route.php` through `Triangle\Router`. A callback receives a data string; during handshake the value may be `null`: + +```php +use Triangle\Router; + +Router::any('/chat', static function (?string $payload) { + return response($payload ?? 'connected'); +}); +``` + +The integration's `response()` helper creates a `Triangle\Ws\Response`. The application defines the payload and response format. Start with a small text payload and verify the handshake and subsequent messages on the expected path. The template also includes a controller action in `app/controller/Index.php`. + +Check this API against the Engine WS dependency actually resolved in the lock: the published tag requires Engine WS 2.x, while the current checkout uses 1.1.x. Do not assume behavior transfers between dependency sets without a runtime integration check. diff --git a/src/pages/projects/triangle-ws/install.mdx b/src/pages/projects/triangle-ws/install.mdx new file mode 100644 index 0000000..188d331 --- /dev/null +++ b/src/pages/projects/triangle-ws/install.mdx @@ -0,0 +1,14 @@ +export const pageTitle = 'Установка Triangle WS' +export const description = 'Расхождения между опубликованным Composer manifest и текущим checkout.' + +# Установка Triangle WS + +`triangle/ws` опубликован как проектный тег `v1.0.4`. Его tagged manifest требует PHP `^8.2`, `triangle/engine:^8.1` и `triangle/engine-ws:^2.0`. Однако `triangle/engine-ws` v2.0.0 требует Engine `^9.0`; одновременно удовлетворить `Engine ^8.1` и это требование невозможно. Поэтому опубликованный manifest WS не имеет разрешимого набора зависимостей в этой связке. Не рассчитывайте на успешный `composer create-project` до исправления релизных constraints. + +Текущий checkout отличается: `composer.json` использует `triangle/engine-ws:^1.1`; lock-файл содержит Engine 8.1.11 и Engine WS 1.1.1. Это состояние исходной копии, а не dependency manifest тега v1.0.4. + +```sh +composer show triangle/ws triangle/engine triangle/engine-ws +``` + +Перед использованием проверьте release manifest и lock выбранного commit. Не устанавливайте текущую preview-комбинацию в production только потому, что локальный lock разрешён. diff --git a/src/pages/projects/triangle-ws/operations.mdx b/src/pages/projects/triangle-ws/operations.mdx new file mode 100644 index 0000000..761f928 --- /dev/null +++ b/src/pages/projects/triangle-ws/operations.mdx @@ -0,0 +1,10 @@ +export const pageTitle = 'Эксплуатация и ограничения WS' +export const description = 'Один worker, broadcast внутри процесса и сетевые границы.' + +# Эксплуатация и ограничения WS + +Конфигурация текущего checkout задаёт `websocket://0.0.0.0:8080`, `Triangle\Ws\App`, `count = 1` и `max_package_size = 10 * 1024 * 1024`. README характеризует шаблон как однопроцессный экспериментальный WebSocket-first проект. Ограничьте входящий порт firewall/TLS proxy, контролируйте размер сообщений и реализуйте прикладную аутентификацию/origin policy. + +`sendToAll()` направляет сообщение соединениям серверов внутри текущего процесса. `sendToGroup()` использует path текущего WebSocket request как scope; это не абстрактная именованная группа. Ни один метод не координирует broadcast между процессами/узлами и не предоставляет shared state. Для горизонтального масштабирования нужен внешний broker/shared-state и routing слой. + +Callbacks выполняются в event-loop контексте: не блокируйте их долгими сетевыми/CPU задачами. Durable message delivery, retries, replay и exactly-once не заявлены. diff --git a/src/pages/projects/triangle-ws/usage.mdx b/src/pages/projects/triangle-ws/usage.mdx new file mode 100644 index 0000000..84f6451 --- /dev/null +++ b/src/pages/projects/triangle-ws/usage.mdx @@ -0,0 +1,18 @@ +export const pageTitle = 'Маршруты и WebSocket payload' +export const description = 'Проверьте route callback на источниках текущего checkout.' + +# Маршруты и WebSocket payload + +На текущем checkout `master` загружает Engine, после чего маршруты регистрируются в `config/route.php` через `Triangle\Router`. Callback получает строку данных; во время handshake значение может быть `null`: + +```php +use Triangle\Router; + +Router::any('/chat', static function (?string $payload) { + return response($payload ?? 'connected'); +}); +``` + +`response()` в интеграции строит `Triangle\Ws\Response`. Payload и формат ответа определяет приложение. Начните с малого текстового payload и проверьте, что handshake и последующие сообщения идут по ожидаемому path. В приложении из шаблона также есть controller action `app/controller/Index.php`. + +Сверьте этот API с зависимостью Engine WS, реально разрешённой в lock: published tag требует Engine WS 2.x, а current checkout — 1.1.x. Не переносите поведение одного набора зависимостей на другой без runtime integration check. diff --git a/src/pages/projects/tunnel.mdx b/src/pages/projects/tunnel.mdx index d77a1af..c302b71 100644 --- a/src/pages/projects/tunnel.mdx +++ b/src/pages/projects/tunnel.mdx @@ -5,14 +5,14 @@ export const description = 'События и очереди между проц [Начало работы](/projects/tunnel/start) · [API и эксплуатация](/projects/tunnel/reference) -Tunnel [`v3.0.3`](https://github.com/localzet/Tunnel/releases/tag/v3.0.3) переносит события и очереди сообщений между процессами Localzet Server 7. `Client` подключается к серверу каналов; сервер маршрутизирует сообщения активным подписчикам и хранит очереди только в памяти. На один процесс сервера действует общий предел в 10 000 ожидающих сообщений. +Tunnel [`v4.0.1`](https://github.com/localzet/Tunnel/releases/tag/v4.0.1) переносит события и очереди сообщений между процессами Localzet Server 7. `Client` подключается к серверу каналов; сервер маршрутизирует сообщения активным подписчикам и хранит очереди только в памяти. На один процесс сервера действует общий предел в 10 000 ожидающих сообщений и 32 МиБ ожидающих данных. Debug-логи не содержат тела запросов, сообщений или исходный текст исключений. ```sh -composer require localzet/tunnel:^3.0 +composer require localzet/tunnel:^4.0 ``` -Версия `3.x` рассчитана на Server 7 и несовместима с исторической линией `2.x`, рассчитанной на Server 4. +Версии `3.x` и `4.x` рассчитаны на Server 7; версия `2.x` — на Server 4. В `4.x` изменены ограничения payload: объекты и циклические массивы отклоняются по умолчанию, а очередь ограничена одновременно количеством сообщений и объёмом данных. Перед обновлением проверьте формат сообщений и согласованно обновите приложения и брокер. Десериализация объектов на входе отключена по умолчанию. Статический opt-in `Client::allowObjectSerialization()` и аргумент конструктора Server предназначены только для доверенных peer в изолированной сети. -Протокол не включает аутентификацию транспортного peer. Ограничьте сетевой доступ внешними ACL и оцените доставку, reconnect, очереди, лимиты памяти и shutdown в целевом развёртывании. +Протокол не включает аутентификацию транспортного peer. Debug-логи показывают операции и статусы, но не содержимое запросов и сообщений. Ограничьте сетевой доступ внешними ACL и оцените доставку, reconnect, очереди, лимиты памяти и shutdown в целевом развёртывании. diff --git a/src/pages/projects/tunnel/reference.mdx b/src/pages/projects/tunnel/reference.mdx index 934305c..98e2416 100644 --- a/src/pages/projects/tunnel/reference.mdx +++ b/src/pages/projects/tunnel/reference.mdx @@ -3,9 +3,9 @@ export const description = 'События, подписки, очереди, re # Tunnel: API и эксплуатация -Релиз [`v3.0.3`](https://github.com/localzet/Tunnel/releases/tag/v3.0.3) добавляет общий лимит в 10 000 ожидающих сообщений на процесс сервера. +Релиз [`v4.0.0`](https://github.com/localzet/Tunnel/releases/tag/v4.0.0) добавил общий предел 32 МиБ ожидающих данных на процесс брокера к лимиту 10 000 сообщений. Версия также запретила объекты и циклические массивы в PHP-serialized payload по умолчанию. Текущий патч-релиз [`v4.0.1`](https://github.com/localzet/Tunnel/releases/tag/v4.0.1) удаляет содержимое сообщений и сырые исключения из debug-логов, не меняя доставку и формат сообщений. -Требуются PHP 8.1+ и Localzet Server `^7.0`. Сервер создаётся как `new localzet\Tunnel\Server($socketName, $debug = false, $allowObjectSerialization = false)`; при заданном socket name он регистрирует один worker через bootstrap Server. `Client` — статический API и рассчитан на один соединённый Tunnel endpoint в каждом PHP-процессе. Версия Tunnel `3.x` рассчитана на Server 7; несовместимая версия `2.x` предназначена для Server 4. +Требуются PHP 8.1+ и Localzet Server `^7.0`. Сервер создаётся как `new localzet\Tunnel\Server($socketName, $debug = false, $allowObjectSerialization = false)`; при заданном socket name он регистрирует один worker через bootstrap Server. `Client` — статический API и рассчитан на один соединённый Tunnel endpoint в каждом PHP-процессе. Tunnel `3.x` и `4.x` рассчитаны на Server 7; линия `2.x` предназначена для Server 4. Версию 4 развёртывайте после проверки payload и приложения: она отвергает объекты и циклические массивы, если opt-in не включён на обеих доверенных сторонах. ## События @@ -15,10 +15,10 @@ export const description = 'События, подписки, очереди, re `enqueue($channels, $data)` добавляет данные в именованную очередь. `watch($channels, $callback, $autoReserve = true)` начинает получать элементы; при авто-резервировании Tunnel запрашивает следующий элемент после завершения callback. `unwatch()` прекращает наблюдение, `reserve()` запрашивает элемент вручную. Очередь хранится только в RAM сервера, не является durable queue и теряется при рестарте. Для побочных эффектов используйте идемпотентные handlers; собственный механизм retry/dead-letter отсутствует. -Все очереди одного процесса делят общий предел в 10 000 ожидающих сообщений. Если enqueue превысит предел, сервер не добавит ни одного сообщения из этого запроса; multi-channel запрос проверяется целиком. `Client::enqueue()` не возвращает подтверждение приёма, поэтому отправитель не может определить по результату вызова, была ли запись отклонена. Учитывайте это при проектировании повторной доставки и собственной обратной связи. +Все очереди одного процесса делят общий предел в 10 000 ожидающих сообщений и 32 МиБ ожидающих данных. Размер учитывается по входному фрейму; при доставке нескольким каналам каждая поставленная копия учитывает этот размер. Если enqueue превысит любой предел, сервер не добавит ни одного сообщения из этого запроса; multi-channel запрос проверяется целиком. `Client::enqueue()` не возвращает подтверждение приёма, поэтому отправитель не может определить по результату вызова, была ли запись отклонена. Учитывайте это при проектировании повторной доставки и собственной обратной связи. ## Формат, безопасность и надёжность Wire protocol по умолчанию сериализует данные PHP. Object deserialization закрыта и на сервере, и на клиенте. Не используйте `new Server(..., allowObjectSerialization: true)` и `Client::allowObjectSerialization()` с недоверенными peer. Передавайте скаляры и массивы; обе стороны должны договориться о формате. Протокол не имеет встроенной аутентификации или TLS, поэтому слушайте loopback либо изолированную сеть и ограничьте доступ внешними ACL. -Reconnect восстанавливает транспорт, но не обеспечивает durable delivery или exactly-once. Тестируйте разрыв соединения, повторную подписку, конкурирующих consumers и shutdown в целевом приложении. Для Server 7 используйте `localzet/tunnel:^3.0`. +Reconnect восстанавливает транспорт, но не обеспечивает durable delivery или exactly-once. Debug-логи содержат названия операций и статусы, но исключают тела запросов и сообщений. Тестируйте разрыв соединения, повторную подписку, конкурирующих consumers и shutdown в целевом приложении. Для Server 7 используйте `localzet/tunnel:^4.0`. diff --git a/src/pages/projects/tunnel/start.mdx b/src/pages/projects/tunnel/start.mdx index 4875826..acaacc1 100644 --- a/src/pages/projects/tunnel/start.mdx +++ b/src/pages/projects/tunnel/start.mdx @@ -3,10 +3,10 @@ export const description = 'Запуск локального сервера Tun # Tunnel: начало работы -Tunnel передаёт события между процессами Localzet Server. Релизная линия `3.x` предназначена для Server 7; линия `2.x` рассчитана на Server 4: +Tunnel 4.0 передаёт события и элементы очередей между процессами Localzet Server 7. Линии `3.x` и `4.x` предназначены для Server 7; `2.x` рассчитана на Server 4. В версии 4 объекты и циклические массивы в PHP-serialized payload отключены по умолчанию, а очередь ограничена 10 000 сообщений и 32 МиБ ожидающих данных: ```sh -composer require localzet/tunnel:^3.0 +composer require localzet/tunnel:^4.0 ``` ## Поднимите сервер каналов From 7b7086006d798b475f39aa4bddaf2d436cc9e62f Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Sat, 21 Nov 2026 12:55:20 +0300 Subject: [PATCH 5/5] docs: clarify version compatibility wording --- src/pages/current/http.mdx | 2 +- src/pages/projects/cron.mdx | 2 +- src/pages/projects/cron/start.mdx | 2 -- src/pages/projects/httpclient.mdx | 2 +- src/pages/projects/httpclient/start.mdx | 2 +- src/pages/projects/psr7.mdx | 2 +- src/pages/projects/psr7/start.mdx | 2 +- src/pages/projects/socketio.mdx | 2 +- src/pages/projects/triangle-console/compatibility.mdx | 2 +- src/pages/projects/triangle-cron.mdx | 2 +- src/pages/projects/triangle-database/compatibility.mdx | 2 +- src/pages/projects/tunnel/reference.mdx | 2 +- src/pages/projects/tunnel/start.mdx | 2 +- 13 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/pages/current/http.mdx b/src/pages/current/http.mdx index 5cf06e3..2fd5092 100644 --- a/src/pages/current/http.mdx +++ b/src/pages/current/http.mdx @@ -26,7 +26,7 @@ $server->onMessage = static function (TcpConnection $connection, Request $reques ## Ответы и файлы -`Response` принимает status, headers и body. Для условных запросов и одиночного byte range используйте `withFileForRequest($request, $path)`: метод учитывает HEAD, ETag и cache validators. Файл передаётся потоком с backpressure. Multipart byte ranges в этой линии не реализованы. +`Response` принимает status, headers и body. Для условных запросов и одиночного byte range используйте `withFileForRequest($request, $path)`: метод учитывает HEAD, ETag и cache validators. Файл передаётся потоком с backpressure. Multipart byte ranges в текущей версии не реализованы. Компрессия по заголовку запроса задаётся явно через `withCompressionForRequest($request)`. Не включайте её без учёта размера и типа ответа. diff --git a/src/pages/projects/cron.mdx b/src/pages/projects/cron.mdx index bf19902..8fb0807 100644 --- a/src/pages/projects/cron.mdx +++ b/src/pages/projects/cron.mdx @@ -11,4 +11,4 @@ Cron запускает повторяющиеся задачи через event composer require localzet/cron:^2.0 ``` -Выпуск [`2.0.1`](https://github.com/localzet/Cron/releases/tag/v2.0.1) рассчитан на Server 7; линия `1.x` относится к Server 4. При удалении cron-задачи планировщик отменяет её ожидающие одноразовые таймеры. Задачи выполняются PHP callbacks внутри процесса. Для нескольких workers задача может выполняться каждым процессом; координацию и защиту от повторного запуска следует обеспечить приложению. +Выпуск [`2.0.1`](https://github.com/localzet/Cron/releases/tag/v2.0.1) рассчитан на Server 7. При удалении cron-задачи планировщик отменяет её ожидающие одноразовые таймеры. Задачи выполняются PHP callbacks внутри процесса. Для нескольких workers задача может выполняться каждым процессом; координацию и защиту от повторного запуска следует обеспечить приложению. diff --git a/src/pages/projects/cron/start.mdx b/src/pages/projects/cron/start.mdx index df919bf..043d19e 100644 --- a/src/pages/projects/cron/start.mdx +++ b/src/pages/projects/cron/start.mdx @@ -9,8 +9,6 @@ Cron добавляет расписания в таймеры процесса composer require localzet/cron:^2.0 ``` -Релиз `2.x` предназначен для Server 7. Линия `1.x` рассчитана на Server 4. - ```php