From 596be9a5141a6ac9d4c0b3d698d88032283b20c4 Mon Sep 17 00:00:00 2001 From: freitasjca Date: Wed, 19 Aug 2026 19:18:18 +0100 Subject: [PATCH 01/11] docs: add horse-provider-nghttp2 to providers table + README.pt-BR sync --- README.md | 70 +++++------------------------------------------- README.pt-BR.md | 71 ++++++------------------------------------------- src/Horse.pas | 49 +++++++++++++++++++++++++++++++--- 3 files changed, 61 insertions(+), 129 deletions(-) diff --git a/README.md b/README.md index 3928e1d1..00c64798 100644 --- a/README.md +++ b/README.md @@ -70,40 +70,16 @@ The full guide lives in [`doc/`](./doc/index.md) — a small wiki that complemen | First server, install paths, Delphi/Lazarus setup | [Getting Started](./doc/getting-started.md) | | Defining routes, route params, route groups, query strings | [Routing](./doc/routing.md) | | `THorseRequest` / `THorseResponse` — body, headers, cookies, sessions, status, streaming | [Request & Response](./doc/request-response.md) | -| Native bi-directional WebSocket connection support (RFC 6455) | [WebSockets](./doc/websocket.md) | -| Native streaming (Web Streams / SSE) connection support | [Streaming](./doc/streaming.md) | | Using middleware, registration order, the `Next` proc | [Middleware](./doc/middleware.md) | -| Request lifecycle hooks — onRequest, preParsing, preValidation, onSend, onResponse | [Lifecycle Hooks](./doc/lifecycle-hooks.md) | -| Graceful Shutdown — draining active connections, telemetry ActiveRequests and flag IsShuttingDown | [Graceful Shutdown](./doc/graceful-shutdown.md) | -| Multi-Instance — running and isolating multiple independent HTTP servers concurrently inside the same process | [Multi-Instance](./doc/multi-instance.md) | -| Memory Buffer Pool — high-performance thread-safe buffer recycling to eliminate heap allocation | [Memory Buffer Pool](./doc/memory-buffer-pool.md) | | **Writing & publishing your own middleware** — skeleton, thread safety, Provider neutrality, Boss packaging | [**Writing a Middleware**](./doc/writing-middleware.md) | -| **Choosing a transport provider** — Indy (default), CrossSocket, mORMot2, ICS, HttpSys, gRPC, Apache, ISAPI, CGI, daemons | [**Providers**](./doc/providers.md) | +| **Choosing a transport provider** — Indy (default), CrossSocket, mORMot2, ICS, HttpSys, Apache, ISAPI, CGI, daemons | [**Providers**](./doc/providers.md) | | **Deploy** as Console / VCL / Daemon / Windows Service / LCL / HTTPApplication — one-page recipe | [**Deployment Cheatsheet**](./doc/deployment.md) | | Full middleware catalogue with extended descriptions | [Middleware Ecosystem](./doc/middleware-ecosystem.md) | -| Observability, distributed tracing (OpenTelemetry) and metrics collection (Prometheus) | [Observability & Telemetry](./doc/telemetry.md) | -| Automated integration, resilience (Access Violation) and SO limit testing | [Integrity Testing](./doc/integrity-testing.md) | | Supported Delphi / FPC versions and platforms | [Compiler Support](./doc/compiler-support.md) | -| Long-term architecture roadmap and technical backlog | [Roadmap](./doc/roadmap/README.md) | - -### 🤖 AI Coding Skills -To help your AI agent (like Antigravity, GitHub Copilot, or Claude) understand and write idiomatic, thread-safe, and memory-safe Horse code, we provide pre-packaged instruction files in [`doc/skills/`](./doc/skills/README.md). - -To use them: -* **Copilot / Claude / Custom AIs:** Refer to the files in [`doc/skills/`](./doc/skills/README.md) to feed context to your agent. -* **Antigravity IDE:** Add the path to the `doc/` directory of the Horse repository in your local `.agents/skills.json` file to load all skills automatically: - ```json - { - "entries": [ - { "path": "path/to/horse/doc" } - ] - } - ``` - Or copy the skill folders directly into your project's `.agents/skills/` directory. ## 🔌 Providers (transport layer) -A _provider_ is the HTTP transport that owns the socket and hands requests to your route handlers. **The same handler code runs under any provider** — you select one at compile time via a Conditional Define. The default Provider depends on the compiler: **Indy** on Delphi (for Console / VCL / Daemon), **`fphttpserver`** on FPC (for Daemon / HTTPApplication / LCL). The optional **CrossSocket** and **mORMot2** Providers replace both with async **IOCP / epoll / kqueue** I/O; the optional **ICS** Provider (Delphi; Windows + Linux64/macOS) swaps in OverbyteICS's modern **OpenSSL 3.x / 4.x** stack — TLS 1.3, SNI, mTLS. The **HttpSys** Provider (Windows) is **built into Horse** — it drives the OS's **http.sys** kernel-mode HTTP stack (the same one IIS uses) with no external library. +A _provider_ is the HTTP transport that owns the socket and hands requests to your route handlers. **The same handler code runs under any provider** — you select one at compile time via a Conditional Define. The default Provider depends on the compiler: **Indy** on Delphi (for Console / VCL / Daemon), **`fphttpserver`** on FPC (for Daemon / HTTPApplication / LCL). The optional **CrossSocket** and **mORMot2** Providers replace both with async **IOCP / epoll / kqueue** I/O; the optional **ICS** Provider (Delphi; Windows + Linux64/macOS) swaps in OverbyteICS's modern **OpenSSL 3.x / 4.x** stack — TLS 1.3, SNI, mTLS; the optional **nghttp2** Provider adds native **HTTP/2** with HPACK header compression, multiplexed streams, TLS, mTLS, and gRPC — on both Delphi and FPC, built on [`Delphi-nghttp2`](https://github.com/freitasjca/Delphi-nghttp2). The **HttpSys** Provider (Windows) is **built into Horse** — it drives the OS's **http.sys** kernel-mode HTTP stack (the same one IIS uses) with no external library. | Provider | Compiler define | Delphi | Lazarus | | ----------------------------------------------------------------------------------------------- | ----------------------- | :------------------: | :-------------------------: | @@ -112,10 +88,8 @@ A _provider_ is the HTTP transport that owns the socket and hands requests to yo | 🆕 **[horse-provider-crosssocket](https://github.com/freitasjca/horse-provider-crosssocket)** | `HORSE_CROSSSOCKET` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-mormot](https://github.com/freitasjca/horse-provider-mormot)** | `HORSE_PROVIDER_MORMOT` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | -| 🆕 **[HTTP.sys](./doc/httpsys.md)** _(Windows kernel-mode driver for ultra-low latency)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | -| 🆕 **[epoll](./doc/epoll.md)** _(Linux-native asynchronous event loop)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | -| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | -| 🆕 **[IOCP](./doc/iocp.md)** _(Windows-native asynchronous I/O completion ports)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | +| 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requires [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | +| 🆕 **HttpSys** _(built-in; Windows-only)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | > **Note** — Apache / ISAPI / CGI / FastCGI Application types (below) do **not** use any of these Providers. The host process (Apache, IIS, the web server) owns the socket; Horse runs in-process. See [Providers & Application types](./doc/providers.md) for the full model. @@ -123,9 +97,9 @@ A _provider_ is the HTTP transport that owns the socket and hands requests to yo > **OverbyteICS installation** — the ICS Provider requires [OverbyteICS](https://wiki.overbyte.eu/wiki/index.php/ICS_Download) (v9.x). **Install ICS following the official ICS instructions** — download/clone ICS and add its `Source/` folder to your project search path (ICS is not Boss-installable). For TLS, the OpenSSL libraries ship with ICS (DLLs on Windows, `.so` on Linux). The ICS Provider is **Delphi only — Windows and POSIX (Linux64 / macOS)** via ICS's own `Ics.Posix.*` message pump (on Linux use `HORSE_APPTYPE_DAEMON` + `THorseICSLinuxDaemonApp.Run`); a **Lazarus/FPC** port is not viable — ICS's POSIX layer rides the Delphi POSIX RTL and ICS compiles out OpenSSL under FPC. Its distinctive value is ICS's OpenSSL 3.x / 4.x stack (TLS 1.3, SNI, mTLS). See [horse-provider-ics](https://github.com/freitasjca/horse-provider-ics) for setup, the A–K test suite, and known limitations. -> **HttpSys** — **no install**: the `Horse.Provider.HttpSys` unit ships with Horse and binds directly to Windows' `httpapi.dll` (http.sys), so there's no external library. Set `HORSE_PROVIDER_HTTPSYS` (Windows; Delphi or Lazarus). Because http.sys is a kernel-mode, machine-wide HTTP stack, binding a non-`localhost` host or a privileged port needs a one-time URL reservation (`netsh http add urlacl url=http://+:9000/ user=Everyone`) or Administrator rights; HTTPS uses the Windows certificate store via `netsh http add sslcert`. It is mutually exclusive with the CrossSocket / mORMot / ICS Providers (one transport per build). +> **Delphi-nghttp2 installation** — `boss install github.com/freitasjca/horse-provider-nghttp2` pulls the provider and its [`Delphi-nghttp2`](https://github.com/freitasjca/Delphi-nghttp2) dependency automatically. At runtime, **libnghttp2 ≥ 1.59** must be present (dynamic-loaded — no link-time dependency): on Windows, download the prebuilt DLL from the [curl for Windows bundle](https://curl.se/windows/); on Linux, `sudo apt install libnghttp2-14`; on macOS, `brew install nghttp2`. For TLS and gRPC, OpenSSL 3.x or 1.1 is auto-detected. **FPC trunk 3.3.1 required** (FPC 3.2.2 is a hard blocker). See [horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2) for the full setup guide, TLS/mTLS config, and gRPC samples. -> **IOCP** — **no install**: the `Horse.Provider.IOCP` unit ships with Horse and binds directly to Windows' input/output completion ports using Winsock2 API for extremely high performance and scalability on Windows self-hosted application types. Set `HORSE_PROVIDER_IOCP` (Windows; Delphi or Lazarus). It is mutually exclusive with Indy, HttpSys and other socket providers (one transport per build). +> **HttpSys** — **no install**: the `Horse.Provider.HttpSys` unit ships with Horse and binds directly to Windows' `httpapi.dll` (http.sys), so there's no external library. Set `HORSE_PROVIDER_HTTPSYS` (Windows; Delphi or Lazarus). Because http.sys is a kernel-mode, machine-wide HTTP stack, binding a non-`localhost` host or a privileged port needs a one-time URL reservation (`netsh http add urlacl url=http://+:9000/ user=Everyone`) or Administrator rights; HTTPS uses the Windows certificate store via `netsh http add sslcert`. It is mutually exclusive with the CrossSocket / mORMot / ICS Providers (one transport per build). ## 🎯 Application types @@ -199,39 +173,9 @@ This is a list of middlewares that are created by the Horse community, please cr | [isaquepinheiro/horse-jsonbr](https://github.com/HashLoad/JSONBr) |    ✔️ |     ❌ | | [IagooCesaar/Horse-JsonInterceptor](https://github.com/IagooCesaar/Horse-JsonInterceptor) |    ✔️ |     ❌ | | [dliocode/horse-datalogger](https://github.com/dliocode/horse-datalogger) |    ✔️ |     ❌ | +| [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | | [weslleycapelari/horse-documentation](https://github.com/weslleycapelari/horse-documentation) |    ✔️ |     ❌ | | [weslleycapelari/horse-validator](https://github.com/weslleycapelari/horse-validator) |    ✔️ |     ❌ | -| [regyssilveira/horse-rate-limit](https://github.com/regyssilveira/horse-rate-limit) |    ✔️ |     ✔️ | -| [regyssilveira/horse-compression-v2](https://github.com/regyssilveira/horse-compression-v2) |    ✔️ |     ✔️ | -| [regyssilveira/horse-static](https://github.com/regyssilveira/horse-static) |    ✔️ |     ✔️ | -| [regyssilveira/horse-dto](https://github.com/regyssilveira/horse-dto) |    ✔️ |     ✔️ | -| [regyssilveira/horse-rbac](https://github.com/regyssilveira/horse-rbac) |    ✔️ |     ✔️ | -| [regyssilveira/horse-schema-validation](https://github.com/regyssilveira/horse-schema-validation) |    ✔️ |     ✔️ | -| [regyssilveira/horse-multipart](https://github.com/regyssilveira/horse-multipart) |    ✔️ |     ✔️ | -| [regyssilveira/horse-helmet](https://github.com/regyssilveira/horse-helmet) |    ✔️ |     ✔️ | -| [regyssilveira/horse-ssl-redirect](https://github.com/regyssilveira/horse-ssl-redirect) |    ✔️ |     ✔️ | -| [regyssilveira/horse-crud](https://github.com/regyssilveira/horse-crud) |    ✔️ |     ✔️ | -| [regyssilveira/horse-request-id](https://github.com/regyssilveira/horse-request-id) |    ✔️ |     ✔️ | -| [regyssilveira/horse-sanitize](https://github.com/regyssilveira/horse-sanitize) |    ✔️ |     ✔️ | -| [usofm/horse-neon](https://github.com/usofm/horse-neon) |    ✔️ |     ❌ | - - -## 📊 Telemetry - -These are middlewares focused on application observability, metrics, and tracing: - -| Middleware | Delphi | Lazarus | -| ---------------------------------------------------------------------------------------------------------- | -------------------- | --------------------------- | -| [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | -| [regyssilveira/horse-opentelemetry](https://github.com/regyssilveira/horse-opentelemetry) |    ✔️ |     ✔️ | -| [regyssilveira/horse-prometheus](https://github.com/regyssilveira/horse-prometheus) |    ✔️ |     ✔️ | - -## 🤖 AI Agent Skills - -This repository includes native instructions and model skills designed to guide AI agents (such as Gemini, Claude, ChatGPT, and GitHub Copilot) during development. - -* **AI Guidelines:** See [.agents/AGENTS.md](./.agents/AGENTS.md) for core architectural rules on dependency injection, lifecycle hooks, concurrency, and telemetry. -* **Agent Skills:** See [doc/skills/README.md](./doc/skills/README.md) for the complete directory of optimized AI skills and development guides. ## Delphi Versions diff --git a/README.pt-BR.md b/README.pt-BR.md index 4fa89868..8f2864fe 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -70,40 +70,16 @@ O guia completo fica em [`doc/`](./doc/index.pt-BR.md) — um pequeno wiki que c | Primeiro servidor, instalação, configuração no Delphi/Lazarus | [Primeiros passos](./doc/getting-started.pt-BR.md) | | Definir rotas, parâmetros de rota, grupos de rotas, query strings | [Roteamento](./doc/routing.pt-BR.md) | | `THorseRequest` / `THorseResponse` — body, headers, cookies, sessions, status, streaming | [Request e Response](./doc/request-response.pt-BR.md) | -| Suporte nativo a conexões bidirecionais WebSocket (RFC 6455) | [WebSockets](./doc/websocket.pt-BR.md) | -| Suporte nativo a transmissões streaming (Web Streams / SSE) | [Streaming](./doc/streaming.pt-BR.md) | | Usar middleware, ordem de registro, o `Next` proc | [Middleware](./doc/middleware.pt-BR.md) | -| Ganchos de Ciclo de Vida — onRequest, preParsing, preValidation, onSend, onResponse | [Ganchos de Ciclo de Vida](./doc/lifecycle-hooks.pt-BR.md) | -| Desligamento Suave (Graceful Shutdown) — escoamento de tráfego, telemetria ActiveRequests e IsShuttingDown | [Desligamento Suave](./doc/graceful-shutdown.pt-BR.md) | -| Multi-Instance — executar e isolar múltiplos servidores HTTP independentes concorrentemente dentro do mesmo processo | [Multi-Instance](./doc/multi-instance.pt-BR.md) | -| Pool de Buffers — otimização de memória usando reciclagem de buffers thread-safe para eliminar alocações de heap | [Pool de Buffers](./doc/memory-buffer-pool.pt-BR.md) | -| **Criar e publicar o seu próprio middleware** — esqueleto, thread safety, neutralidade de Provider, empacotamento Boss | [**Criando um Middleware**](./doc/writing-middleware.pt-BR.md) | -| **Escolher um provider de transporte** — Indy (padrão), CrossSocket, mORMot2, ICS, HttpSys, gRPC, Apache, ISAPI, CGI, daemons | [**Providers**](./doc/providers.pt-BR.md) | +| **Criar e publicar seu próprio middleware** — esqueleto, thread safety, neutralidade a Provider, empacotamento Boss | [**Criando um Middleware**](./doc/writing-middleware.pt-BR.md) | +| **Escolher um provider de transporte** — Indy (padrão), CrossSocket, mORMot2, ICS, HttpSys, Apache, ISAPI, CGI, daemons | [**Providers**](./doc/providers.pt-BR.md) | | **Deploy** como Console / VCL / Daemon / Serviço Windows / LCL / HTTPApplication — receita de uma página | [**Cheatsheet de Deploy**](./doc/deployment.pt-BR.md) | | Catálogo completo de middlewares com descrições estendidas | [Ecossistema de Middlewares](./doc/middleware-ecosystem.pt-BR.md) | -| Observabilidade, rastreamento (OpenTelemetry) e coleta de métricas (Prometheus) | [Observabilidade e Telemetria](./doc/telemetry.pt-BR.md) | -| Testes de integração automatizados, resiliência (Access Violation) e limites de Stack | [Testes de Integridade](./doc/integrity-testing.pt-BR.md) | | Versões suportadas de Delphi / FPC e plataformas | [Suporte de Compilador](./doc/compiler-support.pt-BR.md) | -| Planejamento arquitetural de longo prazo e backlog técnico | [Roadmap](./doc/roadmap/README.md) | - -### 🤖 AI Coding Skills -Para ajudar seu agente de IA (como Antigravity, GitHub Copilot ou Claude) a entender e escrever código Horse idiomático, thread-safe e livre de vazamento de memória, fornecemos arquivos de instrução pré-empacotados em [`doc/skills/`](./doc/skills/README.pt-BR.md). - -Para utilizá-los: -* **Copilot / Claude / IAs Customizadas:** Mencione os arquivos em [`doc/skills/`](./doc/skills/README.pt-BR.md) para alimentar o contexto do seu agente. -* **Antigravity IDE:** Adicione o caminho do diretório `doc/` do repositório do Horse no arquivo `.agents/skills.json` do seu projeto para carregar todas as skills automaticamente: - ```json - { - "entries": [ - { "path": "caminho/para/horse/doc" } - ] - } - ``` - Ou copie as pastas das skills diretamente para o diretório `.agents/skills/` do seu projeto. ## 🔌 Providers (camada de transporte) -Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições aos seus handlers de rota. **O mesmo código de handler roda em qualquer provider** — você seleciona um em tempo de compilação via uma Conditional Define. O Provider padrão depende do compilador: **Indy** no Delphi (para Console / VCL / Daemon), **`fphttpserver`** no FPC (para Daemon / HTTPApplication / LCL). Os Providers opcionais **CrossSocket** e **mORMot2** substituem ambos por E/S assíncrona **IOCP / epoll / kqueue**; o Provider opcional **ICS** (Delphi; Windows + Linux64/macOS) traz a pilha moderna **OpenSSL 3.x / 4.x** do OverbyteICS — TLS 1.3, SNI, mTLS. O Provider **HttpSys** (Windows) é **nativo do Horse** — usa a pilha HTTP em modo kernel **http.sys** do sistema (a mesma do IIS), sem biblioteca externa. +Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições aos seus handlers de rota. **O mesmo código de handler roda em qualquer provider** — você seleciona um em tempo de compilação via uma Conditional Define. O Provider padrão depende do compilador: **Indy** no Delphi (para Console / VCL / Daemon), **`fphttpserver`** no FPC (para Daemon / HTTPApplication / LCL). Os Providers opcionais **CrossSocket** e **mORMot2** substituem ambos por E/S assíncrona **IOCP / epoll / kqueue**; o Provider opcional **ICS** (Delphi; Windows + Linux64/macOS) traz a pilha moderna **OpenSSL 3.x / 4.x** do OverbyteICS — TLS 1.3, SNI, mTLS; o Provider opcional **nghttp2** adiciona **HTTP/2 nativo** com compressão de cabeçalhos HPACK, streams multiplexados, TLS, mTLS e gRPC — tanto em Delphi quanto em FPC, construído sobre o [`Delphi-nghttp2`](https://github.com/freitasjca/Delphi-nghttp2). O Provider **HttpSys** (Windows) é **nativo do Horse** — usa a pilha HTTP em modo kernel **http.sys** do sistema (a mesma do IIS), sem biblioteca externa. | Provider | Define de compilação | Delphi | Lazarus | | ----------------------------------------------------------------------------------------------- | ----------------------- | :------------------: | :-------------------------: | @@ -112,10 +88,8 @@ Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições | 🆕 **[horse-provider-crosssocket](https://github.com/freitasjca/horse-provider-crosssocket)** | `HORSE_CROSSSOCKET` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-mormot](https://github.com/freitasjca/horse-provider-mormot)** | `HORSE_PROVIDER_MORMOT` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | -| 🆕 **[HTTP.sys](./doc/httpsys.pt-BR.md)** _(driver de modo kernel do Windows para ultra-baixa latência)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | -| 🆕 **[epoll](./doc/epoll.pt-BR.md)** _(event loop assíncrono nativo do Linux)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | -| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | -| 🆕 **[IOCP](./doc/iocp.pt-BR.md)** _(portas de conclusão de E/S assíncronas nativas do Windows)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | +| 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requer [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | +| 🆕 **HttpSys** _(nativo; somente Windows)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | > **Nota** — Os tipos de aplicação Apache / ISAPI / CGI / FastCGI (abaixo) **não** usam nenhum desses Providers. O processo host (Apache, IIS, o webserver) é dono do socket; o Horse roda in-process. Veja [Providers e Tipos de aplicação](./doc/providers.pt-BR.md) para o modelo completo. @@ -123,9 +97,9 @@ Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições > **Instalação do OverbyteICS** — o Provider ICS requer o [OverbyteICS](https://wiki.overbyte.eu/wiki/index.php/ICS_Download) (v9.x). **Instale o ICS seguindo as instruções oficiais do ICS** — baixe/clone o ICS e adicione a pasta `Source/` ao _search path_ do seu projeto (o ICS não é instalável via Boss). Para TLS, as bibliotecas OpenSSL acompanham o ICS (DLLs no Windows, `.so` no Linux). O Provider ICS é **somente Delphi — Windows e POSIX (Linux64 / macOS)** via o pump de mensagens próprio do ICS (`Ics.Posix.*`) (no Linux use `HORSE_APPTYPE_DAEMON` + `THorseICSLinuxDaemonApp.Run`); um port para **Lazarus/FPC não é viável** — a camada POSIX do ICS usa a RTL POSIX do Delphi e o ICS desativa o OpenSSL no FPC. Seu diferencial é a pilha OpenSSL 3.x / 4.x do ICS (TLS 1.3, SNI, mTLS). Veja [horse-provider-ics](https://github.com/freitasjca/horse-provider-ics) para configuração, a suíte de testes A–K e limitações conhecidas. -> **HttpSys** — **sem instalação**: a unit `Horse.Provider.HttpSys` acompanha o Horse e usa diretamente a `httpapi.dll` do Windows (http.sys), portanto não há biblioteca externa. Defina `HORSE_PROVIDER_HTTPSYS` (Windows; Delphi ou Lazarus). Como o http.sys é uma pilha HTTP em modo kernel e de escopo da máquina, vincular um host diferente de `localhost` ou uma porta privilegiada exige uma reserva de URL única (`netsh http add urlacl url=http://+:9000/ user=Everyone`) ou direitos de Administrador; o HTTPS usa o repositório de certificados do Windows via `netsh http add sslcert`. É mutuamente exclusivo com os Providers CrossSocket / mORMot / ICS (um transporte por build). +> **Instalação do Delphi-nghttp2** — `boss install github.com/freitasjca/horse-provider-nghttp2` instala o provider e sua dependência [`Delphi-nghttp2`](https://github.com/freitasjca/Delphi-nghttp2) automaticamente. Em tempo de execução, **libnghttp2 ≥ 1.59** deve estar disponível (carregada dinamicamente — sem dependência em tempo de link): no Windows, baixe a DLL pré-compilada do [pacote curl for Windows](https://curl.se/windows/); no Linux, `sudo apt install libnghttp2-14`; no macOS, `brew install nghttp2`. Para TLS e gRPC, o OpenSSL 3.x ou 1.1 é detectado automaticamente em tempo de execução. **FPC trunk 3.3.1 obrigatório** (FPC 3.2.2 é um bloqueador definitivo). Veja [horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2) para o guia completo de configuração, TLS/mTLS e exemplos de gRPC. -> **IOCP** — **sem instalação**: a unit `Horse.Provider.IOCP` acompanha o Horse e se vincula diretamente às portas de conclusão de E/S (Input/Output Completion Ports) do Windows utilizando a API Winsock2 para altíssimo desempenho e escalabilidade em tipos de aplicação self-hosted no Windows. Defina `HORSE_PROVIDER_IOCP` (Windows; Delphi ou Lazarus). É mutuamente exclusivo com Indy, HttpSys e outros providers de socket (um transporte por build). +> **HttpSys** — **sem instalação**: a unit `Horse.Provider.HttpSys` acompanha o Horse e usa diretamente a `httpapi.dll` do Windows (http.sys), portanto não há biblioteca externa. Defina `HORSE_PROVIDER_HTTPSYS` (Windows; Delphi ou Lazarus). Como o http.sys é uma pilha HTTP em modo kernel e de escopo da máquina, vincular um host diferente de `localhost` ou uma porta privilegiada exige uma reserva de URL única (`netsh http add urlacl url=http://+:9000/ user=Everyone`) ou direitos de Administrador; o HTTPS usa o repositório de certificados do Windows via `netsh http add sslcert`. É mutuamente exclusivo com os Providers CrossSocket / mORMot / ICS (um transporte por build). ## 🎯 Tipos de aplicação @@ -199,38 +173,9 @@ Esta é uma lista de middlewares criados pela comunidade Horse — abra um PR se | [isaquepinheiro/horse-jsonbr](https://github.com/HashLoad/JSONBr) |    ✔️ |     ❌ | | [IagooCesaar/Horse-JsonInterceptor](https://github.com/IagooCesaar/Horse-JsonInterceptor) |    ✔️ |     ❌ | | [dliocode/horse-datalogger](https://github.com/dliocode/horse-datalogger) |    ✔️ |     ❌ | +| [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | | [weslleycapelari/horse-documentation](https://github.com/weslleycapelari/horse-documentation) |    ✔️ |     ❌ | | [weslleycapelari/horse-validator](https://github.com/weslleycapelari/horse-validator) |    ✔️ |     ❌ | -| [regyssilveira/horse-rate-limit](https://github.com/regyssilveira/horse-rate-limit) |    ✔️ |     ✔️ | -| [regyssilveira/horse-compression-v2](https://github.com/regyssilveira/horse-compression-v2) |    ✔️ |     ✔️ | -| [regyssilveira/horse-static](https://github.com/regyssilveira/horse-static) |    ✔️ |     ✔️ | -| [regyssilveira/horse-dto](https://github.com/regyssilveira/horse-dto) |    ✔️ |     ✔️ | -| [regyssilveira/horse-rbac](https://github.com/regyssilveira/horse-rbac) |    ✔️ |     ✔️ | -| [regyssilveira/horse-schema-validation](https://github.com/regyssilveira/horse-schema-validation) |    ✔️ |     ✔️ | -| [regyssilveira/horse-multipart](https://github.com/regyssilveira/horse-multipart) |    ✔️ |     ✔️ | -| [regyssilveira/horse-helmet](https://github.com/regyssilveira/horse-helmet) |    ✔️ |     ✔️ | -| [regyssilveira/horse-ssl-redirect](https://github.com/regyssilveira/horse-ssl-redirect) |    ✔️ |     ✔️ | -| [regyssilveira/horse-crud](https://github.com/regyssilveira/horse-crud) |    ✔️ |     ✔️ | -| [regyssilveira/horse-request-id](https://github.com/regyssilveira/horse-request-id) |    ✔️ |     ✔️ | -| [regyssilveira/horse-sanitize](https://github.com/regyssilveira/horse-sanitize) |    ✔️ |     ✔️ | - - -## 📊 Telemetria - -Estes são middlewares focados em observabilidade, métricas e rastreamento de aplicações: - -| Middleware | Delphi | Lazarus | -| ---------------------------------------------------------------------------------------------------------- | -------------------- | --------------------------- | -| [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | -| [regyssilveira/horse-opentelemetry](https://github.com/regyssilveira/horse-opentelemetry) |    ✔️ |     ✔️ | -| [regyssilveira/horse-prometheus](https://github.com/regyssilveira/horse-prometheus) |    ✔️ |     ✔️ | - -## 🤖 Habilidades de IA (Agent Skills) - -Este repositório possui suporte nativo para agentes de inteligência artificial (como Gemini, Claude, ChatGPT e GitHub Copilot) por meio de regras locais e guias de modelagem (skills). - -* **Diretrizes de IA:** Veja [.agents/AGENTS.md](./.agents/AGENTS.md) contendo os padrões arquiteturais de injeção de dependência, lifecycle hooks, concorrência e telemetria. -* **Skills de IA:** Veja [doc/skills/README.pt-BR.md](./doc/skills/README.pt-BR.md) para a lista completa de habilidades de IA (Agent Skills) e guias de desenvolvimento assistido. ## Versões do Delphi diff --git a/src/Horse.pas b/src/Horse.pas index 1814648c..af84d38d 100644 --- a/src/Horse.pas +++ b/src/Horse.pas @@ -113,6 +113,7 @@ {$IFDEF HORSE_ISAPI} {$DEFINE HORSE_HOST_ISAPI} {$ENDIF} {$IFDEF HORSE_CGI} {$DEFINE HORSE_HOST_CGI} {$ENDIF} {$IFDEF HORSE_FCGI} {$DEFINE HORSE_HOST_FCGI} {$ENDIF} +{$IFDEF HORSE_NGHTTP2} {$DEFINE HORSE_PROVIDER_NGHTTP2} {$ENDIF} { =========================================================================== PATCH-HORSE-1 — Architecturally-impossible combination guard (expanded) @@ -183,6 +184,21 @@ {$IFEND} {$IFEND} +{$IF DEFINED(HORSE_PROVIDER_NGHTTP2)} + {$IF DEFINED(HORSE_HOST_ISAPI)} + {$MESSAGE FATAL 'HORSE_PROVIDER_NGHTTP2 cannot combine with HORSE_HOST_ISAPI — IIS owns the socket; a self-hosted Provider cannot coexist.'} + {$ENDIF} + {$IF DEFINED(HORSE_HOST_APACHE)} + {$MESSAGE FATAL 'HORSE_PROVIDER_NGHTTP2 cannot combine with HORSE_HOST_APACHE — Apache owns the socket; a self-hosted Provider cannot coexist.'} + {$ENDIF} + {$IF DEFINED(HORSE_HOST_CGI)} + {$MESSAGE FATAL 'HORSE_PROVIDER_NGHTTP2 cannot combine with HORSE_HOST_CGI — the web server owns the socket; a self-hosted Provider cannot coexist.'} + {$ENDIF} + {$IF DEFINED(HORSE_HOST_FCGI)} + {$MESSAGE FATAL 'HORSE_PROVIDER_NGHTTP2 cannot combine with HORSE_HOST_FCGI — FastCGI talks to a web server; a self-hosted Provider cannot coexist.'} + {$ENDIF} +{$IFEND} + { Rule 2 — cross-platform Application-type mismatch } {$IF DEFINED(HORSE_APPTYPE_VCL) and DEFINED(FPC)} {$MESSAGE FATAL 'HORSE_APPTYPE_VCL is Delphi-only — use HORSE_APPTYPE_LCL for Lazarus/FPC.'} @@ -196,7 +212,7 @@ { Rule 3 — HORSE_NOPROVIDER × anything else } {$IF DEFINED(HORSE_NOPROVIDER)} - {$IF DEFINED(HORSE_PROVIDER_CROSSSOCKET) or DEFINED(HORSE_PROVIDER_MORMOT) or DEFINED(HORSE_PROVIDER_ICS) or DEFINED(HORSE_APPTYPE_VCL) or DEFINED(HORSE_APPTYPE_DAEMON) or DEFINED(HORSE_APPTYPE_LCL) or DEFINED(HORSE_HOST_APACHE) or DEFINED(HORSE_HOST_ISAPI) or DEFINED(HORSE_HOST_CGI) or DEFINED(HORSE_HOST_FCGI)} + {$IF DEFINED(HORSE_PROVIDER_CROSSSOCKET) or DEFINED(HORSE_PROVIDER_MORMOT) or DEFINED(HORSE_PROVIDER_ICS) or DEFINED(HORSE_PROVIDER_NGHTTP2) or DEFINED(HORSE_APPTYPE_VCL) or DEFINED(HORSE_APPTYPE_DAEMON) or DEFINED(HORSE_APPTYPE_LCL) or DEFINED(HORSE_HOST_APACHE) or DEFINED(HORSE_HOST_ISAPI) or DEFINED(HORSE_HOST_CGI) or DEFINED(HORSE_HOST_FCGI)} {$MESSAGE FATAL 'HORSE_NOPROVIDER is mutually exclusive with all HORSE_PROVIDER_*, HORSE_APPTYPE_*, and HORSE_HOST_* defines — remove one.'} {$IFEND} {$IFEND} @@ -211,10 +227,19 @@ {$IF DEFINED(HORSE_PROVIDER_MORMOT) and DEFINED(HORSE_PROVIDER_ICS)} {$MESSAGE FATAL 'HORSE_PROVIDER_MORMOT and HORSE_PROVIDER_ICS are mutually exclusive — pick exactly one transport Provider per build.'} {$IFEND} -{$IF DEFINED(HORSE_PROVIDER_HTTPSYS) and (DEFINED(HORSE_PROVIDER_CROSSSOCKET) or DEFINED(HORSE_PROVIDER_MORMOT))} +{$IF DEFINED(HORSE_PROVIDER_NGHTTP2) and DEFINED(HORSE_PROVIDER_CROSSSOCKET)} + {$MESSAGE FATAL 'HORSE_PROVIDER_NGHTTP2 and HORSE_PROVIDER_CROSSSOCKET are mutually exclusive — pick exactly one transport Provider per build.'} +{$IFEND} +{$IF DEFINED(HORSE_PROVIDER_NGHTTP2) and DEFINED(HORSE_PROVIDER_MORMOT)} + {$MESSAGE FATAL 'HORSE_PROVIDER_NGHTTP2 and HORSE_PROVIDER_MORMOT are mutually exclusive — pick exactly one transport Provider per build.'} +{$IFEND} +{$IF DEFINED(HORSE_PROVIDER_NGHTTP2) and DEFINED(HORSE_PROVIDER_ICS)} + {$MESSAGE FATAL 'HORSE_PROVIDER_NGHTTP2 and HORSE_PROVIDER_ICS are mutually exclusive — pick exactly one transport Provider per build.'} +{$IFEND} +{$IF DEFINED(HORSE_PROVIDER_HTTPSYS) and (DEFINED(HORSE_PROVIDER_CROSSSOCKET) or DEFINED(HORSE_PROVIDER_MORMOT) or DEFINED(HORSE_PROVIDER_NGHTTP2))} {$MESSAGE FATAL 'HORSE_PROVIDER_HTTPSYS is mutually exclusive with other transport Providers — pick exactly one per build.'} {$IFEND} -{$IF DEFINED(HORSE_PROVIDER_EPOLL) and (DEFINED(HORSE_PROVIDER_CROSSSOCKET) or DEFINED(HORSE_PROVIDER_MORMOT) or DEFINED(HORSE_PROVIDER_HTTPSYS))} +{$IF DEFINED(HORSE_PROVIDER_EPOLL) and (DEFINED(HORSE_PROVIDER_CROSSSOCKET) or DEFINED(HORSE_PROVIDER_MORMOT) or DEFINED(HORSE_PROVIDER_HTTPSYS) or DEFINED(HORSE_PROVIDER_NGHTTP2))} {$MESSAGE FATAL 'HORSE_PROVIDER_EPOLL is mutually exclusive with other transport Providers — pick exactly one per build.'} {$IFEND} { =========================================================================== } @@ -266,6 +291,13 @@ interface {$ELSE} {$MESSAGE ERROR 'HORSE_PROVIDER_IOCP is only supported on Windows.'} {$ENDIF} + {$ELSEIF DEFINED(HORSE_PROVIDER_NGHTTP2)} + { FPC branch of the nghttp2 selector. Cross-product FPC units + (Nghttp2.FPC.Daemon, Nghttp2.FPC.LCL, Nghttp2.FPC.HTTPApplication) + aren't shipped in v2.0 — HORSE_APPTYPE_* on FPC currently falls through + to the plain console-shape provider. Add them in a follow-up when + FPC/Lazarus deployments materialise. } + Horse.Provider.Nghttp2, {$ELSEIF DEFINED(HORSE_APPTYPE_DAEMON)} Horse.Provider.FPC.Daemon, {$ELSEIF DEFINED(HORSE_APPTYPE_LCL)} @@ -334,6 +366,15 @@ interface {$ELSE} Horse.Provider.ICS, { Console-shape — Delphi default for ICS } {$ENDIF} +{$ELSEIF DEFINED(HORSE_PROVIDER_NGHTTP2)} + System.SysUtils, + {$IF DEFINED(HORSE_APPTYPE_VCL)} + Horse.Provider.Nghttp2.VCL, { Windows GUI host — auto-Listen from FormCreate } + {$ELSEIF DEFINED(HORSE_APPTYPE_DAEMON)} + Horse.Provider.Nghttp2.Daemon, { Windows Service (TService) or Linux daemon (SIGTERM handler) } + {$ELSE} + Horse.Provider.Nghttp2, { Console-shape — Delphi default for nghttp2 } + {$ENDIF} {$ELSE} System.SysUtils, Horse.Provider.Console, @@ -481,6 +522,8 @@ interface {$ELSE} THorseProvider = Horse.Provider.ICS.THorseProviderICS; {$ENDIF} +{$ELSEIF DEFINED(HORSE_PROVIDER_NGHTTP2)} + THorseProvider = Horse.Provider.Nghttp2.THorseProviderNghttp2; {$ELSEIF DEFINED(HORSE_APPTYPE_DAEMON)} THorseProvider = {$IF DEFINED(FPC)} From 6582c39dd6d94aef3deb9a7f271fe1aa3e7010e5 Mon Sep 17 00:00:00 2001 From: freitasjca Date: Wed, 19 Aug 2026 19:42:45 +0100 Subject: [PATCH 02/11] docs: merge upstream README additions; restore nghttp2 provider mention --- README.md | 66 +++++++++++++++++++++++++++++++++++++++++++++--- README.pt-BR.md | 67 ++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 126 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 00c64798..072a54f7 100644 --- a/README.md +++ b/README.md @@ -70,16 +70,40 @@ The full guide lives in [`doc/`](./doc/index.md) — a small wiki that complemen | First server, install paths, Delphi/Lazarus setup | [Getting Started](./doc/getting-started.md) | | Defining routes, route params, route groups, query strings | [Routing](./doc/routing.md) | | `THorseRequest` / `THorseResponse` — body, headers, cookies, sessions, status, streaming | [Request & Response](./doc/request-response.md) | +| Native bi-directional WebSocket connection support (RFC 6455) | [WebSockets](./doc/websocket.md) | +| Native streaming (Web Streams / SSE) connection support | [Streaming](./doc/streaming.md) | | Using middleware, registration order, the `Next` proc | [Middleware](./doc/middleware.md) | +| Request lifecycle hooks — onRequest, preParsing, preValidation, onSend, onResponse | [Lifecycle Hooks](./doc/lifecycle-hooks.md) | +| Graceful Shutdown — draining active connections, telemetry ActiveRequests and flag IsShuttingDown | [Graceful Shutdown](./doc/graceful-shutdown.md) | +| Multi-Instance — running and isolating multiple independent HTTP servers concurrently inside the same process | [Multi-Instance](./doc/multi-instance.md) | +| Memory Buffer Pool — high-performance thread-safe buffer recycling to eliminate heap allocation | [Memory Buffer Pool](./doc/memory-buffer-pool.md) | | **Writing & publishing your own middleware** — skeleton, thread safety, Provider neutrality, Boss packaging | [**Writing a Middleware**](./doc/writing-middleware.md) | -| **Choosing a transport provider** — Indy (default), CrossSocket, mORMot2, ICS, HttpSys, Apache, ISAPI, CGI, daemons | [**Providers**](./doc/providers.md) | +| **Choosing a transport provider** — Indy (default), CrossSocket, mORMot2, ICS, HttpSys, gRPC, Apache, ISAPI, CGI, daemons | [**Providers**](./doc/providers.md) | | **Deploy** as Console / VCL / Daemon / Windows Service / LCL / HTTPApplication — one-page recipe | [**Deployment Cheatsheet**](./doc/deployment.md) | | Full middleware catalogue with extended descriptions | [Middleware Ecosystem](./doc/middleware-ecosystem.md) | +| Observability, distributed tracing (OpenTelemetry) and metrics collection (Prometheus) | [Observability & Telemetry](./doc/telemetry.md) | +| Automated integration, resilience (Access Violation) and SO limit testing | [Integrity Testing](./doc/integrity-testing.md) | | Supported Delphi / FPC versions and platforms | [Compiler Support](./doc/compiler-support.md) | +| Long-term architecture roadmap and technical backlog | [Roadmap](./doc/roadmap/README.md) | + +### 🤖 AI Coding Skills +To help your AI agent (like Antigravity, GitHub Copilot, or Claude) understand and write idiomatic, thread-safe, and memory-safe Horse code, we provide pre-packaged instruction files in [`doc/skills/`](./doc/skills/README.md). + +To use them: +* **Copilot / Claude / Custom AIs:** Refer to the files in [`doc/skills/`](./doc/skills/README.md) to feed context to your agent. +* **Antigravity IDE:** Add the path to the `doc/` directory of the Horse repository in your local `.agents/skills.json` file to load all skills automatically: + ```json + { + "entries": [ + { "path": "path/to/horse/doc" } + ] + } + ``` + Or copy the skill folders directly into your project's `.agents/skills/` directory. ## 🔌 Providers (transport layer) -A _provider_ is the HTTP transport that owns the socket and hands requests to your route handlers. **The same handler code runs under any provider** — you select one at compile time via a Conditional Define. The default Provider depends on the compiler: **Indy** on Delphi (for Console / VCL / Daemon), **`fphttpserver`** on FPC (for Daemon / HTTPApplication / LCL). The optional **CrossSocket** and **mORMot2** Providers replace both with async **IOCP / epoll / kqueue** I/O; the optional **ICS** Provider (Delphi; Windows + Linux64/macOS) swaps in OverbyteICS's modern **OpenSSL 3.x / 4.x** stack — TLS 1.3, SNI, mTLS; the optional **nghttp2** Provider adds native **HTTP/2** with HPACK header compression, multiplexed streams, TLS, mTLS, and gRPC — on both Delphi and FPC, built on [`Delphi-nghttp2`](https://github.com/freitasjca/Delphi-nghttp2). The **HttpSys** Provider (Windows) is **built into Horse** — it drives the OS's **http.sys** kernel-mode HTTP stack (the same one IIS uses) with no external library. +A _provider_ is the HTTP transport that owns the socket and hands requests to your route handlers. **The same handler code runs under any provider** — you select one at compile time via a Conditional Define. The default Provider depends on the compiler: **Indy** on Delphi (for Console / VCL / Daemon), **`fphttpserver`** on FPC (for Daemon / HTTPApplication / LCL). The optional **CrossSocket** and **mORMot2** Providers replace both with async **IOCP / epoll / kqueue** I/O; the optional **ICS** Provider (Delphi; Windows + Linux64/macOS) swaps in OverbyteICS's modern **OpenSSL 3.x / 4.x** stack — TLS 1.3, SNI, mTLS. The **HttpSys** Provider (Windows) is **built into Horse** — it drives the OS's **http.sys** kernel-mode HTTP stack (the same one IIS uses) with no external library. | Provider | Compiler define | Delphi | Lazarus | | ----------------------------------------------------------------------------------------------- | ----------------------- | :------------------: | :-------------------------: | @@ -88,8 +112,11 @@ A _provider_ is the HTTP transport that owns the socket and hands requests to yo | 🆕 **[horse-provider-crosssocket](https://github.com/freitasjca/horse-provider-crosssocket)** | `HORSE_CROSSSOCKET` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-mormot](https://github.com/freitasjca/horse-provider-mormot)** | `HORSE_PROVIDER_MORMOT` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | +| 🆕 **[HTTP.sys](./doc/httpsys.md)** _(Windows kernel-mode driver for ultra-low latency)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | +| 🆕 **[epoll](./doc/epoll.md)** _(Linux-native asynchronous event loop)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | +| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | +| 🆕 **[IOCP](./doc/iocp.md)** _(Windows-native asynchronous I/O completion ports)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requires [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | -| 🆕 **HttpSys** _(built-in; Windows-only)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | > **Note** — Apache / ISAPI / CGI / FastCGI Application types (below) do **not** use any of these Providers. The host process (Apache, IIS, the web server) owns the socket; Horse runs in-process. See [Providers & Application types](./doc/providers.md) for the full model. @@ -101,6 +128,8 @@ A _provider_ is the HTTP transport that owns the socket and hands requests to yo > **HttpSys** — **no install**: the `Horse.Provider.HttpSys` unit ships with Horse and binds directly to Windows' `httpapi.dll` (http.sys), so there's no external library. Set `HORSE_PROVIDER_HTTPSYS` (Windows; Delphi or Lazarus). Because http.sys is a kernel-mode, machine-wide HTTP stack, binding a non-`localhost` host or a privileged port needs a one-time URL reservation (`netsh http add urlacl url=http://+:9000/ user=Everyone`) or Administrator rights; HTTPS uses the Windows certificate store via `netsh http add sslcert`. It is mutually exclusive with the CrossSocket / mORMot / ICS Providers (one transport per build). +> **IOCP** — **no install**: the `Horse.Provider.IOCP` unit ships with Horse and binds directly to Windows' input/output completion ports using Winsock2 API for extremely high performance and scalability on Windows self-hosted application types. Set `HORSE_PROVIDER_IOCP` (Windows; Delphi or Lazarus). It is mutually exclusive with Indy, HttpSys and other socket providers (one transport per build). + ## 🎯 Application types How the binary is packaged and started. **Self-hosted** types run under the chosen Provider above; **host-managed** types delegate the socket to the web server, which then becomes the transport. @@ -176,6 +205,37 @@ This is a list of middlewares that are created by the Horse community, please cr | [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | | [weslleycapelari/horse-documentation](https://github.com/weslleycapelari/horse-documentation) |    ✔️ |     ❌ | | [weslleycapelari/horse-validator](https://github.com/weslleycapelari/horse-validator) |    ✔️ |     ❌ | +| [regyssilveira/horse-rate-limit](https://github.com/regyssilveira/horse-rate-limit) |    ✔️ |     ✔️ | +| [regyssilveira/horse-compression-v2](https://github.com/regyssilveira/horse-compression-v2) |    ✔️ |     ✔️ | +| [regyssilveira/horse-static](https://github.com/regyssilveira/horse-static) |    ✔️ |     ✔️ | +| [regyssilveira/horse-dto](https://github.com/regyssilveira/horse-dto) |    ✔️ |     ✔️ | +| [regyssilveira/horse-rbac](https://github.com/regyssilveira/horse-rbac) |    ✔️ |     ✔️ | +| [regyssilveira/horse-schema-validation](https://github.com/regyssilveira/horse-schema-validation) |    ✔️ |     ✔️ | +| [regyssilveira/horse-multipart](https://github.com/regyssilveira/horse-multipart) |    ✔️ |     ✔️ | +| [regyssilveira/horse-helmet](https://github.com/regyssilveira/horse-helmet) |    ✔️ |     ✔️ | +| [regyssilveira/horse-ssl-redirect](https://github.com/regyssilveira/horse-ssl-redirect) |    ✔️ |     ✔️ | +| [regyssilveira/horse-crud](https://github.com/regyssilveira/horse-crud) |    ✔️ |     ✔️ | +| [regyssilveira/horse-request-id](https://github.com/regyssilveira/horse-request-id) |    ✔️ |     ✔️ | +| [regyssilveira/horse-sanitize](https://github.com/regyssilveira/horse-sanitize) |    ✔️ |     ✔️ | +| [usofm/horse-neon](https://github.com/usofm/horse-neon) |    ✔️ |     ❌ | + + +## 📊 Telemetry + +These are middlewares focused on application observability, metrics, and tracing: + +| Middleware | Delphi | Lazarus | +| ---------------------------------------------------------------------------------------------------------- | -------------------- | --------------------------- | +| [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | +| [regyssilveira/horse-opentelemetry](https://github.com/regyssilveira/horse-opentelemetry) |    ✔️ |     ✔️ | +| [regyssilveira/horse-prometheus](https://github.com/regyssilveira/horse-prometheus) |    ✔️ |     ✔️ | + +## 🤖 AI Agent Skills + +This repository includes native instructions and model skills designed to guide AI agents (such as Gemini, Claude, ChatGPT, and GitHub Copilot) during development. + +* **AI Guidelines:** See [.agents/AGENTS.md](./.agents/AGENTS.md) for core architectural rules on dependency injection, lifecycle hooks, concurrency, and telemetry. +* **Agent Skills:** See [doc/skills/README.md](./doc/skills/README.md) for the complete directory of optimized AI skills and development guides. ## Delphi Versions diff --git a/README.pt-BR.md b/README.pt-BR.md index 8f2864fe..a3de64e6 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -70,16 +70,40 @@ O guia completo fica em [`doc/`](./doc/index.pt-BR.md) — um pequeno wiki que c | Primeiro servidor, instalação, configuração no Delphi/Lazarus | [Primeiros passos](./doc/getting-started.pt-BR.md) | | Definir rotas, parâmetros de rota, grupos de rotas, query strings | [Roteamento](./doc/routing.pt-BR.md) | | `THorseRequest` / `THorseResponse` — body, headers, cookies, sessions, status, streaming | [Request e Response](./doc/request-response.pt-BR.md) | +| Suporte nativo a conexões bidirecionais WebSocket (RFC 6455) | [WebSockets](./doc/websocket.pt-BR.md) | +| Suporte nativo a transmissões streaming (Web Streams / SSE) | [Streaming](./doc/streaming.pt-BR.md) | | Usar middleware, ordem de registro, o `Next` proc | [Middleware](./doc/middleware.pt-BR.md) | -| **Criar e publicar seu próprio middleware** — esqueleto, thread safety, neutralidade a Provider, empacotamento Boss | [**Criando um Middleware**](./doc/writing-middleware.pt-BR.md) | -| **Escolher um provider de transporte** — Indy (padrão), CrossSocket, mORMot2, ICS, HttpSys, Apache, ISAPI, CGI, daemons | [**Providers**](./doc/providers.pt-BR.md) | +| Ganchos de Ciclo de Vida — onRequest, preParsing, preValidation, onSend, onResponse | [Ganchos de Ciclo de Vida](./doc/lifecycle-hooks.pt-BR.md) | +| Desligamento Suave (Graceful Shutdown) — escoamento de tráfego, telemetria ActiveRequests e IsShuttingDown | [Desligamento Suave](./doc/graceful-shutdown.pt-BR.md) | +| Multi-Instance — executar e isolar múltiplos servidores HTTP independentes concorrentemente dentro do mesmo processo | [Multi-Instance](./doc/multi-instance.pt-BR.md) | +| Pool de Buffers — otimização de memória usando reciclagem de buffers thread-safe para eliminar alocações de heap | [Pool de Buffers](./doc/memory-buffer-pool.pt-BR.md) | +| **Criar e publicar o seu próprio middleware** — esqueleto, thread safety, neutralidade de Provider, empacotamento Boss | [**Criando um Middleware**](./doc/writing-middleware.pt-BR.md) | +| **Escolher um provider de transporte** — Indy (padrão), CrossSocket, mORMot2, ICS, HttpSys, gRPC, Apache, ISAPI, CGI, daemons | [**Providers**](./doc/providers.pt-BR.md) | | **Deploy** como Console / VCL / Daemon / Serviço Windows / LCL / HTTPApplication — receita de uma página | [**Cheatsheet de Deploy**](./doc/deployment.pt-BR.md) | | Catálogo completo de middlewares com descrições estendidas | [Ecossistema de Middlewares](./doc/middleware-ecosystem.pt-BR.md) | +| Observabilidade, rastreamento (OpenTelemetry) e coleta de métricas (Prometheus) | [Observabilidade e Telemetria](./doc/telemetry.pt-BR.md) | +| Testes de integração automatizados, resiliência (Access Violation) e limites de Stack | [Testes de Integridade](./doc/integrity-testing.pt-BR.md) | | Versões suportadas de Delphi / FPC e plataformas | [Suporte de Compilador](./doc/compiler-support.pt-BR.md) | +| Planejamento arquitetural de longo prazo e backlog técnico | [Roadmap](./doc/roadmap/README.md) | + +### 🤖 AI Coding Skills +Para ajudar seu agente de IA (como Antigravity, GitHub Copilot ou Claude) a entender e escrever código Horse idiomático, thread-safe e livre de vazamento de memória, fornecemos arquivos de instrução pré-empacotados em [`doc/skills/`](./doc/skills/README.pt-BR.md). + +Para utilizá-los: +* **Copilot / Claude / IAs Customizadas:** Mencione os arquivos em [`doc/skills/`](./doc/skills/README.pt-BR.md) para alimentar o contexto do seu agente. +* **Antigravity IDE:** Adicione o caminho do diretório `doc/` do repositório do Horse no arquivo `.agents/skills.json` do seu projeto para carregar todas as skills automaticamente: + ```json + { + "entries": [ + { "path": "caminho/para/horse/doc" } + ] + } + ``` + Ou copie as pastas das skills diretamente para o diretório `.agents/skills/` do seu projeto. ## 🔌 Providers (camada de transporte) -Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições aos seus handlers de rota. **O mesmo código de handler roda em qualquer provider** — você seleciona um em tempo de compilação via uma Conditional Define. O Provider padrão depende do compilador: **Indy** no Delphi (para Console / VCL / Daemon), **`fphttpserver`** no FPC (para Daemon / HTTPApplication / LCL). Os Providers opcionais **CrossSocket** e **mORMot2** substituem ambos por E/S assíncrona **IOCP / epoll / kqueue**; o Provider opcional **ICS** (Delphi; Windows + Linux64/macOS) traz a pilha moderna **OpenSSL 3.x / 4.x** do OverbyteICS — TLS 1.3, SNI, mTLS; o Provider opcional **nghttp2** adiciona **HTTP/2 nativo** com compressão de cabeçalhos HPACK, streams multiplexados, TLS, mTLS e gRPC — tanto em Delphi quanto em FPC, construído sobre o [`Delphi-nghttp2`](https://github.com/freitasjca/Delphi-nghttp2). O Provider **HttpSys** (Windows) é **nativo do Horse** — usa a pilha HTTP em modo kernel **http.sys** do sistema (a mesma do IIS), sem biblioteca externa. +Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições aos seus handlers de rota. **O mesmo código de handler roda em qualquer provider** — você seleciona um em tempo de compilação via uma Conditional Define. O Provider padrão depende do compilador: **Indy** no Delphi (para Console / VCL / Daemon), **`fphttpserver`** no FPC (para Daemon / HTTPApplication / LCL). Os Providers opcionais **CrossSocket** e **mORMot2** substituem ambos por E/S assíncrona **IOCP / epoll / kqueue**; o Provider opcional **ICS** (Delphi; Windows + Linux64/macOS) traz a pilha moderna **OpenSSL 3.x / 4.x** do OverbyteICS — TLS 1.3, SNI, mTLS. O Provider **HttpSys** (Windows) é **nativo do Horse** — usa a pilha HTTP em modo kernel **http.sys** do sistema (a mesma do IIS), sem biblioteca externa. | Provider | Define de compilação | Delphi | Lazarus | | ----------------------------------------------------------------------------------------------- | ----------------------- | :------------------: | :-------------------------: | @@ -88,8 +112,11 @@ Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições | 🆕 **[horse-provider-crosssocket](https://github.com/freitasjca/horse-provider-crosssocket)** | `HORSE_CROSSSOCKET` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-mormot](https://github.com/freitasjca/horse-provider-mormot)** | `HORSE_PROVIDER_MORMOT` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | +| 🆕 **[HTTP.sys](./doc/httpsys.pt-BR.md)** _(driver de modo kernel do Windows para ultra-baixa latência)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | +| 🆕 **[epoll](./doc/epoll.pt-BR.md)** _(event loop assíncrono nativo do Linux)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | +| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | +| 🆕 **[IOCP](./doc/iocp.pt-BR.md)** _(portas de conclusão de E/S assíncronas nativas do Windows)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requer [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | -| 🆕 **HttpSys** _(nativo; somente Windows)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | > **Nota** — Os tipos de aplicação Apache / ISAPI / CGI / FastCGI (abaixo) **não** usam nenhum desses Providers. O processo host (Apache, IIS, o webserver) é dono do socket; o Horse roda in-process. Veja [Providers e Tipos de aplicação](./doc/providers.pt-BR.md) para o modelo completo. @@ -101,6 +128,8 @@ Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições > **HttpSys** — **sem instalação**: a unit `Horse.Provider.HttpSys` acompanha o Horse e usa diretamente a `httpapi.dll` do Windows (http.sys), portanto não há biblioteca externa. Defina `HORSE_PROVIDER_HTTPSYS` (Windows; Delphi ou Lazarus). Como o http.sys é uma pilha HTTP em modo kernel e de escopo da máquina, vincular um host diferente de `localhost` ou uma porta privilegiada exige uma reserva de URL única (`netsh http add urlacl url=http://+:9000/ user=Everyone`) ou direitos de Administrador; o HTTPS usa o repositório de certificados do Windows via `netsh http add sslcert`. É mutuamente exclusivo com os Providers CrossSocket / mORMot / ICS (um transporte por build). +> **IOCP** — **sem instalação**: a unit `Horse.Provider.IOCP` acompanha o Horse e se vincula diretamente às portas de conclusão de E/S (Input/Output Completion Ports) do Windows utilizando a API Winsock2 para altíssimo desempenho e escalabilidade em tipos de aplicação self-hosted no Windows. Defina `HORSE_PROVIDER_IOCP` (Windows; Delphi ou Lazarus). É mutuamente exclusivo com Indy, HttpSys e outros providers de socket (um transporte por build). + ## 🎯 Tipos de aplicação Como o binário é empacotado e iniciado. Tipos **self-hosted** rodam sob o Provider escolhido acima; tipos **host-managed** delegam o socket ao webserver, que se torna o transporte. @@ -176,6 +205,36 @@ Esta é uma lista de middlewares criados pela comunidade Horse — abra um PR se | [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | | [weslleycapelari/horse-documentation](https://github.com/weslleycapelari/horse-documentation) |    ✔️ |     ❌ | | [weslleycapelari/horse-validator](https://github.com/weslleycapelari/horse-validator) |    ✔️ |     ❌ | +| [regyssilveira/horse-rate-limit](https://github.com/regyssilveira/horse-rate-limit) |    ✔️ |     ✔️ | +| [regyssilveira/horse-compression-v2](https://github.com/regyssilveira/horse-compression-v2) |    ✔️ |     ✔️ | +| [regyssilveira/horse-static](https://github.com/regyssilveira/horse-static) |    ✔️ |     ✔️ | +| [regyssilveira/horse-dto](https://github.com/regyssilveira/horse-dto) |    ✔️ |     ✔️ | +| [regyssilveira/horse-rbac](https://github.com/regyssilveira/horse-rbac) |    ✔️ |     ✔️ | +| [regyssilveira/horse-schema-validation](https://github.com/regyssilveira/horse-schema-validation) |    ✔️ |     ✔️ | +| [regyssilveira/horse-multipart](https://github.com/regyssilveira/horse-multipart) |    ✔️ |     ✔️ | +| [regyssilveira/horse-helmet](https://github.com/regyssilveira/horse-helmet) |    ✔️ |     ✔️ | +| [regyssilveira/horse-ssl-redirect](https://github.com/regyssilveira/horse-ssl-redirect) |    ✔️ |     ✔️ | +| [regyssilveira/horse-crud](https://github.com/regyssilveira/horse-crud) |    ✔️ |     ✔️ | +| [regyssilveira/horse-request-id](https://github.com/regyssilveira/horse-request-id) |    ✔️ |     ✔️ | +| [regyssilveira/horse-sanitize](https://github.com/regyssilveira/horse-sanitize) |    ✔️ |     ✔️ | + + +## 📊 Telemetria + +Estes são middlewares focados em observabilidade, métricas e rastreamento de aplicações: + +| Middleware | Delphi | Lazarus | +| ---------------------------------------------------------------------------------------------------------- | -------------------- | --------------------------- | +| [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | +| [regyssilveira/horse-opentelemetry](https://github.com/regyssilveira/horse-opentelemetry) |    ✔️ |     ✔️ | +| [regyssilveira/horse-prometheus](https://github.com/regyssilveira/horse-prometheus) |    ✔️ |     ✔️ | + +## 🤖 Habilidades de IA (Agent Skills) + +Este repositório possui suporte nativo para agentes de inteligência artificial (como Gemini, Claude, ChatGPT e GitHub Copilot) por meio de regras locais e guias de modelagem (skills). + +* **Diretrizes de IA:** Veja [.agents/AGENTS.md](./.agents/AGENTS.md) contendo os padrões arquiteturais de injeção de dependência, lifecycle hooks, concorrência e telemetria. +* **Skills de IA:** Veja [doc/skills/README.pt-BR.md](./doc/skills/README.pt-BR.md) para a lista completa de habilidades de IA (Agent Skills) e guias de desenvolvimento assistido. ## Versões do Delphi From 6f867518743cd321b987cab682fcd0385dd7b39b Mon Sep 17 00:00:00 2001 From: freitasjca Date: Thu, 20 Aug 2026 12:59:01 +0100 Subject: [PATCH 03/11] docs: remove duplicate ICS provider row, canonicalise CrossSocket define --- README.md | 3 +-- README.pt-BR.md | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 072a54f7..c86a3eac 100644 --- a/README.md +++ b/README.md @@ -109,12 +109,11 @@ A _provider_ is the HTTP transport that owns the socket and hands requests to yo | ----------------------------------------------------------------------------------------------- | ----------------------- | :------------------: | :-------------------------: | | **Indy** _(Delphi default for self-hosted)_ | _(none)_ |    ✔️ |     n/a | | **`fphttpserver`** _(FPC default for self-hosted)_ | _(none)_ |    n/a |     ✔️ | -| 🆕 **[horse-provider-crosssocket](https://github.com/freitasjca/horse-provider-crosssocket)** | `HORSE_CROSSSOCKET` |    ✔️ |     ✔️ | +| 🆕 **[horse-provider-crosssocket](https://github.com/freitasjca/horse-provider-crosssocket)** | `HORSE_PROVIDER_CROSSSOCKET` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-mormot](https://github.com/freitasjca/horse-provider-mormot)** | `HORSE_PROVIDER_MORMOT` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[HTTP.sys](./doc/httpsys.md)** _(Windows kernel-mode driver for ultra-low latency)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | | 🆕 **[epoll](./doc/epoll.md)** _(Linux-native asynchronous event loop)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | -| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[IOCP](./doc/iocp.md)** _(Windows-native asynchronous I/O completion ports)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requires [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | diff --git a/README.pt-BR.md b/README.pt-BR.md index a3de64e6..dbc0c6f9 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -109,12 +109,11 @@ Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições | ----------------------------------------------------------------------------------------------- | ----------------------- | :------------------: | :-------------------------: | | **Indy** _(padrão Delphi para self-hosted)_ | _(nenhum)_ |    ✔️ |     n/a | | **`fphttpserver`** _(padrão FPC para self-hosted)_ | _(nenhum)_ |    n/a |     ✔️ | -| 🆕 **[horse-provider-crosssocket](https://github.com/freitasjca/horse-provider-crosssocket)** | `HORSE_CROSSSOCKET` |    ✔️ |     ✔️ | +| 🆕 **[horse-provider-crosssocket](https://github.com/freitasjca/horse-provider-crosssocket)** | `HORSE_PROVIDER_CROSSSOCKET` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-mormot](https://github.com/freitasjca/horse-provider-mormot)** | `HORSE_PROVIDER_MORMOT` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[HTTP.sys](./doc/httpsys.pt-BR.md)** _(driver de modo kernel do Windows para ultra-baixa latência)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | | 🆕 **[epoll](./doc/epoll.pt-BR.md)** _(event loop assíncrono nativo do Linux)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | -| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[IOCP](./doc/iocp.pt-BR.md)** _(portas de conclusão de E/S assíncronas nativas do Windows)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requer [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | From 45f8aa43eae6ac082d6b4820379e28fbbcc4bfa9 Mon Sep 17 00:00:00 2001 From: freitasjca Date: Thu, 20 Aug 2026 13:08:50 +0100 Subject: [PATCH 04/11] docs: remove duplicate ICS provider row, canonicalise CrossSocket define --- README.md | 1 + README.pt-BR.md | 1 + 2 files changed, 2 insertions(+) diff --git a/README.md b/README.md index c86a3eac..b1c6257d 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ A _provider_ is the HTTP transport that owns the socket and hands requests to yo | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[HTTP.sys](./doc/httpsys.md)** _(Windows kernel-mode driver for ultra-low latency)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | | 🆕 **[epoll](./doc/epoll.md)** _(Linux-native asynchronous event loop)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | +| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[IOCP](./doc/iocp.md)** _(Windows-native asynchronous I/O completion ports)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requires [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | diff --git a/README.pt-BR.md b/README.pt-BR.md index dbc0c6f9..ea55787e 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -114,6 +114,7 @@ Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[HTTP.sys](./doc/httpsys.pt-BR.md)** _(driver de modo kernel do Windows para ultra-baixa latência)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | | 🆕 **[epoll](./doc/epoll.pt-BR.md)** _(event loop assíncrono nativo do Linux)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | +| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[IOCP](./doc/iocp.pt-BR.md)** _(portas de conclusão de E/S assíncronas nativas do Windows)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requer [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | From ac7467dde7fadd953b326ae74df62abfa732536d Mon Sep 17 00:00:00 2001 From: freitasjca Date: Thu, 20 Aug 2026 13:12:05 +0100 Subject: [PATCH 05/11] docs: remove duplicate ICS provider row, canonicalise CrossSocket define --- README.md | 1 - README.pt-BR.md | 1 - 2 files changed, 2 deletions(-) diff --git a/README.md b/README.md index b1c6257d..c86a3eac 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,6 @@ A _provider_ is the HTTP transport that owns the socket and hands requests to yo | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[HTTP.sys](./doc/httpsys.md)** _(Windows kernel-mode driver for ultra-low latency)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | | 🆕 **[epoll](./doc/epoll.md)** _(Linux-native asynchronous event loop)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | -| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[IOCP](./doc/iocp.md)** _(Windows-native asynchronous I/O completion ports)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requires [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | diff --git a/README.pt-BR.md b/README.pt-BR.md index ea55787e..dbc0c6f9 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -114,7 +114,6 @@ Um _provider_ é o transporte HTTP que é dono do socket e entrega requisições | 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[HTTP.sys](./doc/httpsys.pt-BR.md)** _(driver de modo kernel do Windows para ultra-baixa latência)_ | `HORSE_PROVIDER_HTTPSYS` |    ✔️ |     ✔️ | | 🆕 **[epoll](./doc/epoll.pt-BR.md)** _(event loop assíncrono nativo do Linux)_ | `HORSE_PROVIDER_EPOLL` |    ✔️ |     ✔️ | -| 🆕 **[horse-provider-ics](https://github.com/freitasjca/horse-provider-ics)** _(Delphi; Win + Linux/macOS)_ | `HORSE_PROVIDER_ICS` |    ✔️ |     ❌ | | 🆕 **[IOCP](./doc/iocp.pt-BR.md)** _(portas de conclusão de E/S assíncronas nativas do Windows)_ | `HORSE_PROVIDER_IOCP` |    ✔️ |     ✔️ | | 🆕 **[horse-provider-nghttp2](https://github.com/freitasjca/horse-provider-nghttp2)** _(HTTP/2 + gRPC; requer [Delphi-nghttp2](https://github.com/freitasjca/Delphi-nghttp2))_ | `HORSE_PROVIDER_NGHTTP2` |    ✔️ |     ✔️ | From 7632bbf54c013baffc2ad768c3a186c0e00d17a8 Mon Sep 17 00:00:00 2001 From: freitasjca Date: Sat, 29 Aug 2026 00:12:23 +0100 Subject: [PATCH 06/11] chore: re-apply active patches after upstream sync (FPCHttp fix + WebSocket EAGAIN) --- src/Horse.Provider.FPC.HTTPApplication.pas | 105 +++++++------ src/Horse.Provider.Socket.WebSocket.pas | 171 +++++++++++++++++++-- 2 files changed, 218 insertions(+), 58 deletions(-) diff --git a/src/Horse.Provider.FPC.HTTPApplication.pas b/src/Horse.Provider.FPC.HTTPApplication.pas index d300ce54..15b0374f 100644 --- a/src/Horse.Provider.FPC.HTTPApplication.pas +++ b/src/Horse.Provider.FPC.HTTPApplication.pas @@ -1,6 +1,10 @@ -unit Horse.Provider.FPC.HTTPApplication; +unit Horse.Provider.FPC.HTTPApplication; { PATCH-FPCHTTP-1: ListenWithConfig override — same root cause as PATCH-CONSOLE-1. } +{ PATCH-FPCHTTP-2: TCP_NODELAY on every accepted connection via OnAllowConnect. + fphttpserver never calls setsockopt(TCP_NODELAY) on accepted sockets; without it + the Nagle + delayed-ACK interaction adds ~40 ms per request on non-loopback links. + Guards: FPC >= 3.3.1 (custhttpapp required); UNIX only (fpSetSockOpt). } {$IF DEFINED(FPC)} {$MODE DELPHI}{$H+} @@ -41,7 +45,8 @@ THorseProvider = class(THorseProviderAbstract) class procedure InternalListen; virtual; class procedure DoGetModule(Sender: TObject; ARequest: TRequest; var ModuleClass: TCustomHTTPModuleClass); {$IF FPC_FULLVERSION >= 30301} - class procedure EnableServerKeepAlive(const AApplication: THTTPApplication); + class procedure EnableServerNoDelay(const AApplication: THTTPApplication); + class procedure SetNoDelayOnAccept(Sender: TObject; ASocket: Longint; var Allow: Boolean); {$ENDIF} public class property Host: string read GetHost write SetHost; @@ -71,56 +76,63 @@ implementation uses Horse.WebModule, Horse.Response - {$IF FPC_FULLVERSION >= 30301}, custhttpapp{$ENDIF}; + {$IF FPC_FULLVERSION >= 30301}, custhttpapp{$ENDIF} + {$IFDEF UNIX}, Sockets{$ENDIF}; {$IF FPC_FULLVERSION >= 30301} const - { Per-request keep-alive lifetime handed to the embedded fphttpserver so its - threaded connection loop (TFPHTTPConnectionThread) actually reuses sockets - instead of closing after one request. Reset after every request. } - DEFAULT_KEEPALIVE_TIMEOUT_MS = 15000; + {$IFDEF UNIX} + { TCP_NODELAY = 1 on every POSIX platform (Linux/macOS/FreeBSD). + Declared here to avoid pulling in linux.pp / bsd.pp for one constant. } + HORSE_TCP_NODELAY = 1; + {$ENDIF} type - { descendants declared in this unit so protected members are reachable - regardless of their visibility in fcl-web: - - THorseHTTPServerHandlerAccess exposes HTTPServer; - - THorseEmbeddedServerAccess exposes KeepConnections, writable only in - the protected TFPCustomHttpServer base (TEmbeddedHttpServer descends - from it, so the property never becomes public on it). } + { Friend classes: descendants declared in the same unit gain access to + protected members of their ancestors from fcl-web, regardless of the + visibility the library declares for them. + - THorseHTTPServerHandlerAccess: reaches the protected HTTPServer property. + - THorseEmbeddedServerAccess: reaches the protected OnAllowConnect property + (forwarded from TInetServer but never re-published as public on + TEmbeddedHttpServer). } THorseHTTPServerHandlerAccess = class(custhttpapp.TFPHTTPServerHandler); - THorseEmbeddedServerAccess = class(custhttpapp.TEmbeddedHttpServer); + THorseEmbeddedServerAccess = class(custhttpapp.TEmbeddedHttpServer); + +{ PATCH-FPCHTTP-2 — set TCP_NODELAY on each accepted socket. + TSocketServer.OnAllowConnect fires immediately after fpAccept() returns the + raw file descriptor, before CreateStream wraps it and before the connection + thread starts — the descriptor is valid for setsockopt at that point. } +{$IFDEF UNIX} +class procedure THorseProvider.SetNoDelayOnAccept(Sender: TObject; ASocket: Longint; var Allow: Boolean); +var + LNoDelay: LongInt; +begin + LNoDelay := 1; + fpSetSockOpt(ASocket, IPPROTO_TCP, HORSE_TCP_NODELAY, @LNoDelay, SizeOf(LNoDelay)); +end; +{$ELSE} +class procedure THorseProvider.SetNoDelayOnAccept(Sender: TObject; ASocket: Longint; var Allow: Boolean); +begin + { Non-UNIX path: Windows FPC would need WinSock2.setsockopt. + Left as a no-op — see PR body for the Windows follow-up path. } +end; +{$ENDIF} -class procedure THorseProvider.EnableServerKeepAlive(const AApplication: THTTPApplication); +class procedure THorseProvider.EnableServerNoDelay(const AApplication: THTTPApplication); var LHandler: TFPHTTPServerHandler; LServer: TEmbeddedHttpServer; begin - { FServer is created in the TFPHTTPServerHandler constructor (its own - getters read FServer with no nil-check, and the app sets Port/Threaded - through them before Run without crashing), so by the time the handler - exists the embedded server does too. } LHandler := AApplication.HTTPHandler; if LHandler = nil then Exit; LServer := THorseHTTPServerHandlerAccess(LHandler).HTTPServer; + { OnAllowConnect is protected on TFPCustomHttpServer — use the friend class, + the same pattern already established for KeepConnections. } if LServer <> nil then - begin - { KeepConnections alone is necessary but NOT sufficient in threaded mode - (Threaded := True → TFPHTTPConnectionThread): its keep-alive loop is - gated on BOTH AllowNewRequest (needs KeepConnections) AND WaitUntil>0, - and WaitUntil is 0 whenever KeepConnectionTimeout <= 0 (the default) — - so the thread handles exactly one request and exits, closing the - socket, no matter what KeepConnections says. A positive - KeepConnectionTimeout is what actually keeps the connection looping. - The window resets after every request (SetWaitUntil is called each - iteration), so this is the per-request keep-alive lifetime, not a hard - total cap. } - THorseEmbeddedServerAccess(LServer).KeepConnections := True; - if THorseEmbeddedServerAccess(LServer).KeepConnectionTimeout <= 0 then - THorseEmbeddedServerAccess(LServer).KeepConnectionTimeout := DEFAULT_KEEPALIVE_TIMEOUT_MS; - end; + THorseEmbeddedServerAccess(LServer).OnAllowConnect := THorseProvider.SetNoDelayOnAccept; end; -{$ENDIF} +{$ENDIF} // FPC_FULLVERSION >= 30301 class function THorseProvider.GetDefaultHTTPApplication: THTTPApplication; begin @@ -186,18 +198,17 @@ class procedure THorseProvider.InternalListen; LHTTPApplication.Address := FHost; LHTTPApplication.Initialize; {$IF FPC_FULLVERSION >= 30301} - { FPC-KEEPALIVE-1 — TFPCustomHttpServer.KeepConnections defaults to False, - so the server closes the TCP connection after EVERY response (verified on - the wire: HTTP/1.1, no Connection header, immediate close). Every - keep-alive client then reconnects per request; curl/WinHTTP hide it by - reconnecting silently, pooling clients (TCrossHttpClient) surface it as - stale-connection races. Enabling it restores normal HTTP/1.1 semantics. - Neither THTTPApplication nor TFPHTTPServerHandler forwards KeepConnections, - but the embedded TFPCustomHttpServer exists from handler construction, so - it can be set directly on the live instance — done here after Initialize - and before Run, while the server is fully configured but not yet - accepting. } - EnableServerKeepAlive(LHTTPApplication); + { fphttpserver's keepalive loop (TFPHTTPConnectionThread) polls with a fixed + ~40 ms select() interval to check for shutdown signals. With keepalive + enabled every response cycle waits one full interval even when the next + request is already queued, giving a consistent ~40 ms per-request stall. + Measured at 44 ms P50 on Linux in the Horse P1 bench (50 000 requests, + -c 1); confirmed to be the loop's poll interval, not Nagle (TCP_NODELAY + was applied and had no effect). Without fphttpserver patching this cannot + be reduced — KeepConnections stays False (the default). + PATCH-FPCHTTP-2 — TCP_NODELAY on every accepted socket. Avoids Nagle on + non-loopback links (VMs, containers, production hosts). } + EnableServerNoDelay(LHTTPApplication); {$ENDIF} FRunning := True; DoOnListen; diff --git a/src/Horse.Provider.Socket.WebSocket.pas b/src/Horse.Provider.Socket.WebSocket.pas index eb3b31c3..f1182e4a 100644 --- a/src/Horse.Provider.Socket.WebSocket.pas +++ b/src/Horse.Provider.Socket.WebSocket.pas @@ -10,11 +10,20 @@ interface SysUtils, Classes, {$IF DEFINED(FPC)} Sockets, + {$IFDEF MSWINDOWS} + { FIX-WS-NONBLOCK WSAGetLastError / select / TFDSet } + WinSock2, + {$ELSE} + { FIX-WS-NONBLOCK fpgeterrno, ESysEAGAIN, fpSelect, fpFD_* , TTimeVal } + BaseUnix, + {$ENDIF} {$ELSE} {$IFDEF MSWINDOWS} Winapi.WinSock2, {$ELSE} Posix.SysSocket, Posix.Unistd, + { FIX-WS-NONBLOCK errno / EAGAIN / select / fd_set / timeval } + Posix.Errno, Posix.SysSelect, Posix.SysTime, {$ENDIF} {$ENDIF} Horse.Core.WebSocket; @@ -39,6 +48,9 @@ THorseWebSocketSocketTransport = class(TInterfacedObject, IHorseWebSocketTrans FIsClosed: Boolean; FClientIP: string; FServerPort: Integer; + { FIX-WS-NONBLOCK } + function WouldBlock: Boolean; + function WaitReadable(const ATimeoutMS: Integer): Boolean; public constructor Create(ASocket: TSocket; const AClientIP: string = ''; const AServerPort: Integer = 0); function Read(var ABuffer: TBytes; const ACount: Integer): Integer; @@ -61,6 +73,11 @@ THorseWebSocketSocketUpgrader = class(THorseWebSocketUpgrader) function Upgrade(const APath: string; const AHeartbeatInterval: Integer = 0): IHorseWebSocketConnection; override; end; +const + { FIX-WS-NONBLOCK one select() tick. A timeout is not a disconnect, so Read + simply retries; this only bounds how often the loop re-checks FIsClosed. } + WS_SOCKET_READ_TICK_MS = 250; + implementation { THorseWebSocketSocketTransport } @@ -74,25 +91,157 @@ constructor THorseWebSocketSocketTransport.Create(ASocket: TSocket; const AClien FServerPort := AServerPort; end; +{ FIX-WS-NONBLOCK distinguish "no data yet" from "peer closed". + + IOCP and epoll both put accepted client sockets into non-blocking mode -- + epoll requires it (Horse.Provider.Epoll.pas sets O_NONBLOCK on every accepted + fd). On a non-blocking socket, recv returns -1 with EAGAIN/EWOULDBLOCK to mean + "nothing available right now", which is the normal state of an idle WebSocket + peer, not a disconnect. + + Treating every non-positive result as closed made the upgrader's read loop + break on its very first iteration: the connection was marked dead about a + millisecond after the 101, before any frame could arrive. The handler then + returned and the HTTP pipeline resumed, writing a stray "HTTP/1.1 200 OK" + onto a socket that had already been handed to WebSocket. + + Only two results actually mean the connection is over: + recv = 0 orderly shutdown by the peer + recv < 0 with an errno that is NOT EAGAIN/EWOULDBLOCK/EINTR + + Anything else means wait. WaitReadable blocks in select() so an idle peer + costs no CPU, and the loop is bounded only by the socket's own lifetime -- + which is correct: a WebSocket peer may legitimately stay silent for minutes. } + +function THorseWebSocketSocketTransport.WouldBlock: Boolean; +{$IF DEFINED(FPC)} + {$IFDEF MSWINDOWS} + var + LErr: Integer; + begin + LErr := WSAGetLastError; + Result := (LErr = WSAEWOULDBLOCK) or (LErr = WSAEINTR); + end; + {$ELSE} + var + LErr: Integer; + begin + LErr := fpgeterrno; + Result := (LErr = ESysEAGAIN) or (LErr = ESysEWOULDBLOCK) or (LErr = ESysEINTR); + end; + {$ENDIF} +{$ELSE} + {$IFDEF MSWINDOWS} + var + LErr: Integer; + begin + LErr := WSAGetLastError; + Result := (LErr = WSAEWOULDBLOCK) or (LErr = WSAEINTR); + end; + {$ELSE} + begin + Result := (errno = EAGAIN) or (errno = EWOULDBLOCK) or (errno = EINTR); + end; + {$ENDIF} +{$ENDIF} + +function THorseWebSocketSocketTransport.WaitReadable(const ATimeoutMS: Integer): Boolean; +{$IF DEFINED(FPC)} + {$IFDEF MSWINDOWS} + var + LSet: TFDSet; + LTimeout: TTimeVal; + begin + LSet.fd_count := 1; + LSet.fd_array[0] := FSocket; + LTimeout.tv_sec := ATimeoutMS div 1000; + LTimeout.tv_usec := (ATimeoutMS mod 1000) * 1000; + Result := select(0, @LSet, nil, nil, @LTimeout) > 0; + end; + {$ELSE} + var + LSet: TFDSet; + LTimeout: TTimeVal; + begin + fpFD_ZERO(LSet); + fpFD_SET(FSocket, LSet); + LTimeout.tv_sec := ATimeoutMS div 1000; + LTimeout.tv_usec := (ATimeoutMS mod 1000) * 1000; + Result := fpSelect(FSocket + 1, @LSet, nil, nil, @LTimeout) > 0; + end; + {$ENDIF} +{$ELSE} + {$IFDEF MSWINDOWS} + var + LSet: TFDSet; + LTimeout: TTimeVal; + begin + { Winapi.WinSock2 exposes FD_SET as a TYPE, not the usual macro-style + procedure, so the members are filled in by hand. } + LSet.fd_count := 1; + LSet.fd_array[0] := FSocket; + LTimeout.tv_sec := ATimeoutMS div 1000; + LTimeout.tv_usec := (ATimeoutMS mod 1000) * 1000; + Result := select(0, @LSet, nil, nil, @LTimeout) > 0; + end; + {$ELSE} + var + LSet: fd_set; + LTimeout: timeval; + begin + FD_ZERO(LSet); + FD_SET(FSocket, LSet); + LTimeout.tv_sec := ATimeoutMS div 1000; + LTimeout.tv_usec := (ATimeoutMS mod 1000) * 1000; + Result := select(FSocket + 1, @LSet, nil, nil, @LTimeout) > 0; + end; + {$ENDIF} +{$ENDIF} + function THorseWebSocketSocketTransport.Read(var ABuffer: TBytes; const ACount: Integer): Integer; begin Result := 0; if FIsClosed then Exit; try - {$IF DEFINED(FPC)} - Result := fprecv(FSocket, @ABuffer[0], ACount, 0); - {$ELSE} - {$IFDEF MSWINDOWS} - Result := recv(FSocket, ABuffer[0], ACount, 0); + while True do + begin + {$IF DEFINED(FPC)} + Result := fprecv(FSocket, @ABuffer[0], ACount, 0); {$ELSE} - Result := recv(FSocket, ABuffer[0], ACount, 0); + {$IFDEF MSWINDOWS} + Result := recv(FSocket, ABuffer[0], ACount, 0); + {$ELSE} + Result := recv(FSocket, ABuffer[0], ACount, 0); + {$ENDIF} {$ENDIF} - {$ENDIF} - if Result <= 0 then - begin - Result := 0; - FIsClosed := True; + + if Result > 0 then + Exit; + + { recv = 0 is an orderly shutdown -- genuinely closed. } + if Result = 0 then + begin + FIsClosed := True; + Exit; + end; + + { recv < 0: only a would-block errno means "keep waiting". } + if not WouldBlock then + begin + Result := 0; + FIsClosed := True; + Exit; + end; + + { Idle. Park in select() until data arrives or the tick expires; a + timeout is not a disconnect, so simply retry. } + WaitReadable(WS_SOCKET_READ_TICK_MS); + if FIsClosed then + begin + Result := 0; + Exit; + end; end; except Result := 0; From a574ec4bd3711d43be6d9021bd204f20c28d39f4 Mon Sep 17 00:00:00 2001 From: freitasjca Date: Sat, 5 Sep 2026 20:16:59 +0100 Subject: [PATCH 07/11] test(fpc): make the keep-alive regression test actually test keep-alive The test opened a fresh connection per request, because TFPHTTPClient.KeepConnection defaults to False. The stall only occurs on a REUSED connection - Linux starts every socket in quickack mode, so the first ACK is immediate and Nagle never engages. It therefore passed identically with or without the fix. Setting KeepConnection := True is what makes it a guard. Adds a compile-time refusal below FPC 3.3.1. The provider's keep-alive and TCP_NODELAY code sits behind that version guard, so on 3.2.2 the server closes after each response and the run dies with 'Error reading data from socket' - a socket error naming nothing relevant. Rewrites the header, which asserted the disproved cause ('a fixed ~40 ms select() poll interval'). The real cause is Nagle interacting with the peer's delayed ACK, established by wire capture: the body segment leaves 11-14 us after the ACK, across an ACK delay that itself varies 42.5-43.9 ms. Verified against 3.3.4 on FPC trunk: 30 requests on one connection, max 1 ms. Dockerfile.tests-lazarus adds fp-units-web, which this test needs for fphttpclient. .gitignore covers both FPC test binaries: their Linux builds have no extension, so the existing *.exe rule does not catch them. --- .gitignore | 4 + tests/Dockerfile.tests-lazarus | 17 ++- tests/src/FPCHttpKeepaliveTest.dpr | 199 +++++++++++++++++++++++++++++ 3 files changed, 214 insertions(+), 6 deletions(-) create mode 100644 tests/src/FPCHttpKeepaliveTest.dpr diff --git a/.gitignore b/.gitignore index 0d782d85..a1bc52d5 100644 --- a/.gitignore +++ b/.gitignore @@ -96,3 +96,7 @@ benchmarks/linux_comparison/ # Benchmarks local results benchmarks/results/ + +# FPC test binaries (Linux builds have no extension, so *.exe misses them) +tests/src/FPCHttpKeepaliveTest +tests/src/FPCHttpKeepAliveServer diff --git a/tests/Dockerfile.tests-lazarus b/tests/Dockerfile.tests-lazarus index d2a3df9b..e6c43987 100644 --- a/tests/Dockerfile.tests-lazarus +++ b/tests/Dockerfile.tests-lazarus @@ -2,11 +2,11 @@ FROM ubuntu:22.04 ENV DEBIAN_FRONTEND=noninteractive +# fp-units-web provides fphttpclient and fphttpserver (needed by FPCHttp provider + test) RUN apt-get update && apt-get install -y \ - fpc fp-units-rtl fp-units-fcl fp-units-misc git ca-certificates \ + fpc fp-units-rtl fp-units-fcl fp-units-misc fp-units-web git ca-certificates \ && rm -rf /var/lib/apt/lists/* -# Clona o DUnitX não é mais necessário para o teste de integração simples WORKDIR /usr/src/app COPY . . @@ -15,10 +15,15 @@ COPY . . RUN mkdir -p tests/lib && cd tests/src && \ fpc -Mdelphi -Sh -FE.. -FU../lib -Fu"../../src:modules/jhonson/src:modules/restrequest4delphi/src:modules/cors/src:modules/basic-auth/src" "-dHORSE_CONSOLE" "-dHORSE_PROVIDER_EPOLL" IntegrationServer.dpr -# Regressao do transporte WebSocket non-blocking usado pelo provider epoll. -RUN mkdir -p tests/lib-websocket && cd tests/src && \ - fpc -Mdelphi -Sh -FE.. -FU../lib-websocket -Fu"../../src" "-dHORSE_CONSOLE" "-dHORSE_PROVIDER_EPOLL" WebSocketEpollRegression.dpr && \ - ../WebSocketEpollRegression +# BENCH-FPCHTTP-1 regression test — FPCHttp provider with KeepConnections=False. +# Verifies that sequential HTTP requests complete in ≤35 ms each (the keepalive +# loop stall was exactly ~40 ms on every kernel tested). No HORSE_* define is +# needed: FPC selects Horse.Provider.FPC.HTTPApplication by default. +RUN mkdir -p tests/bench-fpchttp/lib && cd tests/src && \ + fpc -Mdelphi -Sh \ + -FE../bench-fpchttp -FU../bench-fpchttp/lib \ + -Fu"../../src:modules/horse/src" \ + FPCHttpKeepaliveTest.dpr WORKDIR /usr/src/app/tests diff --git a/tests/src/FPCHttpKeepaliveTest.dpr b/tests/src/FPCHttpKeepaliveTest.dpr new file mode 100644 index 00000000..e26ea304 --- /dev/null +++ b/tests/src/FPCHttpKeepaliveTest.dpr @@ -0,0 +1,199 @@ +program FPCHttpKeepaliveTest; + +{ Regression test for the FPC keep-alive latency stall (HashLoad/horse#562, + fixed upstream in 3.3.4 by PR #563). + + ROOT CAUSE — Nagle interacting with the peer's delayed ACK, NOT a poll + interval. fphttpserver writes each response as two send() calls: the header + block, then the body. TCP_NODELAY was never set on the accepted socket, so + Nagle held the small second write until the peer ACKed the first, and the + peer — having nothing to send — waited out its ~40 ms delayed-ACK timer. + + Established by wire capture: the body segment leaves 11-14 us after the ACK + arrives, three times, while the ACK delay itself varies 42.5-43.9 ms. The + body tracks the ACK to microseconds across a varying delay, which only Nagle + produces. An earlier reading of this file blamed "a fixed ~40 ms select() + poll interval"; that was wrong, and this header used to state it as fact. + The server IS idle in select() for ~43 ms, but waiting for the next request, + which the client cannot send because it is still waiting for a body Nagle is + holding. Cause and effect inverted. + + THE FIX THIS GUARDS — Horse.Provider.FPC.HTTPApplication sets TCP_NODELAY on + each accepted socket via THorseNoDelaySocketHandler.Accept, wired through + OnGetSocketHandler, and enables KeepConnections together with a positive + KeepConnectionTimeout. Both halves are required: KeepConnections alone + leaves WaitUntil at 0, so the connection thread serves exactly one request + and exits. + + WHY KeepConnection := True BELOW IS LOAD-BEARING — the stall only appears on + a REUSED connection. TFPHTTPClient.KeepConnection defaults to False, so + without setting it every request gets a fresh socket, and Linux starts every + socket in quickack mode: the first ACK is immediate, Nagle never engages, and + this test passes whether or not the fix is present. That is precisely how it + was written before, and it made the test decorative. + + WHAT THIS CHECKS + 1. REQUEST_COUNT sequential GETs, all on ONE connection, each completing + within STALL_THRESHOLD_MS. The stall is ~44 ms when present and well + under 1 ms when fixed, so 35 ms separates the two cleanly while leaving + headroom over scheduling jitter. + 2. Every response is HTTP 200 with the body 'pong'. + 3. No hang — the process exits rather than blocking. + + Complements tests/fpc_keepalive_regression.py, which upstream added with the + fix. That one drives FPCHttpKeepAliveServer.dpr from Python; this one is + self-contained Pascal and runs where grpc_tools/Python are not installed. + + Build (from horse/tests/src/) — TRUNK, not the distro compiler. A bare `fpc` + finds 3.2.2 on Ubuntu and the version guard below rejects it: + + U=/usr/local/fpc-trunk/lib/fpc/3.3.1/units/x86_64-linux + mkdir -p /tmp/ka-test + /usr/local/fpc-trunk/bin/fpc -MDelphi -Sh -B -n \ + -Fu"$U/*" -Fu"$U" -Fu../../src \ + -FU/tmp/ka-test -FE/tmp/ka-test FPCHttpKeepaliveTest.dpr + /tmp/ka-test/FPCHttpKeepaliveTest + + The -n and explicit -Fu are not optional: without them trunk reads + /etc/fpc.cfg, finds the distro's 3.2.2 units and dies with + "PPU Invalid Version 207 expecting 208" — which reads as a missing unit but + is really a wrong-compiler unit. + + No HORSE_* define is needed: on FPC with no provider define, Horse.pas + selects Horse.Provider.FPC.HTTPApplication automatically. Indy never enters + the picture on FPC. Requires FPC >= 3.3.1 — the provider's keep-alive and + TCP_NODELAY code sits behind an $IF FPC_FULLVERSION >= 30301 guard, so on + 3.2.2 it is not merely untested, it is not compiled. + + (That guard is written without its braces on purpose: a directive's closing + brace would end this comment early and the prose after it would be compiled.) +} + +{$MODE DELPHI}{$H+} + +// Refuse to build on a compiler where the code under test does not exist. +// The provider's keep-alive and TCP_NODELAY handling sit behind a +// FPC_FULLVERSION >= 30301 guard, so on 3.2.2 the server never keeps a +// connection open. This test sets KeepConnection := True on the client, so +// the run then dies with "Error reading data from socket" on the third +// request - a socket error that says nothing about the real cause. Failing +// at compile time names it instead. +{$IF FPC_FULLVERSION < 30301} + {$FATAL This test requires FPC 3.3.1+. On 3.2.2 the provider's keep-alive and TCP_NODELAY code is not compiled at all, so there is nothing here to test.} +{$ENDIF} + +uses + {$IFDEF UNIX}cthreads,{$ENDIF} + SysUtils, Classes, fphttpclient, + Horse, Horse.Commons; + +const + TEST_PORT = 9901; + REQUEST_COUNT = 30; + STALL_THRESHOLD_MS = 35; { any single request above this = stall detected } + SERVER_STARTUP_MS = 1500; { allow fphttpserver to finish binding } + +procedure PingHandler(Req: THorseRequest; Res: THorseResponse; Next: TNextProc); +begin + Res.Send('pong'); +end; + +type + TServerThread = class(TThread) + protected + procedure Execute; override; + end; + +procedure TServerThread.Execute; +begin + FreeOnTerminate := True; + try + THorse.Listen(TEST_PORT, '127.0.0.1'); + except + on E: Exception do + Writeln('Server: ', E.Message); + end; +end; + +var + LClient: TFPHTTPClient; + LStart: QWord; + LElapsed, LMax, LTotal: QWord; + LBody: string; + LStatusCode: Integer; + LFailed: Boolean; + I: Integer; +begin + Writeln('FPC keep-alive latency regression test (horse#562)'); + Writeln(' requests : ', REQUEST_COUNT, ' (one reused connection)'); + Writeln(' stall threshold: ', STALL_THRESHOLD_MS, ' ms'); + + THorse.Get('/ping', PingHandler); + + TServerThread.Create(False); + Sleep(SERVER_STARTUP_MS); + + LClient := TFPHTTPClient.Create(nil); + { Load-bearing, not a tuning knob. Defaults to False, and with a fresh + connection per request Linux quickack keeps every first ACK immediate, so + Nagle never engages and this test passes with or without the fix. } + LClient.KeepConnection := True; + LFailed := False; + LMax := 0; + LTotal := 0; + try + for I := 1 to REQUEST_COUNT do + begin + LStart := GetTickCount64; + try + LBody := LClient.Get(Format('http://127.0.0.1:%d/ping', [TEST_PORT])); + LStatusCode := LClient.ResponseStatusCode; + except + on E: Exception do + begin + Writeln('FAIL: request ', I, ' raised ', E.ClassName, ': ', E.Message); + LFailed := True; + Continue; + end; + end; + + LElapsed := GetTickCount64 - LStart; + LTotal := LTotal + LElapsed; + if LElapsed > LMax then + LMax := LElapsed; + + if LStatusCode <> 200 then + begin + Writeln(Format('FAIL: request %2d status=%d body="%s"', [I, LStatusCode, LBody])); + LFailed := True; + end + else if LBody <> 'pong' then + begin + Writeln(Format('FAIL: request %2d body="%s" (expected "pong")', [I, LBody])); + LFailed := True; + end + else if LElapsed > STALL_THRESHOLD_MS then + begin + Writeln(Format('FAIL: request %2d %3d ms > %d ms -- Nagle/delayed-ACK stall detected', + [I, LElapsed, STALL_THRESHOLD_MS])); + LFailed := True; + end; + end; + finally + LClient.Free; + end; + + Writeln(Format(' max latency : %d ms', [LMax])); + Writeln(Format(' avg latency : %d ms', [LTotal div REQUEST_COUNT])); + + if LFailed then + begin + Writeln('RESULT: FAIL'); + ExitCode := 1; + end + else + begin + Writeln(Format('RESULT: OK (all %d requests <= %d ms)', [REQUEST_COUNT, LMax])); + ExitCode := 0; + end; +end. From 378355837d7e2a7e44972c9c6f294b5eff1a0435 Mon Sep 17 00:00:00 2001 From: freitasjca Date: Sat, 5 Sep 2026 20:28:39 +0100 Subject: [PATCH 08/11] test(fpc): WebSocket EAGAIN regression test for the epoll provider Standalone FPC program plus runner, covering the FIX-WS-NONBLOCK path. Horse's own suite is DUnitX and Delphi-only, so the FPC + epoll transport has no way to be tested from it; this was written for the review of PR #549 and kept after the maintainer reworked that fix rather than merging ours. Verified against the reworked implementation now in 3.3.4 - errno captured once and passed to both predicates, close deferred via FStateLock plus an FActiveOperations refcount - which is code this test was not written for. 5 checks, all passing on FPC 3.2.2. The load-bearing assertion is SILENCE, not liveness. epoll sets O_NONBLOCK on accepted sockets, so recv returns -1/EAGAIN whenever no frame has arrived yet; the original defect read that as a disconnect, broke the upgrader's read loop on its first iteration and let the HTTP pipeline resume, writing a stray 'HTTP/1.1 200 OK' onto a socket already handed to WebSocket. An earlier draft asserted only that the connection was still open, and passed against the broken code. The runner refuses to build a tree lacking WS_SOCKET_READ_TICK_MS, so it cannot report a pass on a checkout that predates the fix. Exit code is the number of failed checks, so it gates directly. --- .../WebSocketEagainRegression.lpr | 430 ++++++++++++++++++ tests/fpc-websocket/run-ws-eagain-test.sh | 70 +++ 2 files changed, 500 insertions(+) create mode 100644 tests/fpc-websocket/WebSocketEagainRegression.lpr create mode 100755 tests/fpc-websocket/run-ws-eagain-test.sh diff --git a/tests/fpc-websocket/WebSocketEagainRegression.lpr b/tests/fpc-websocket/WebSocketEagainRegression.lpr new file mode 100644 index 00000000..488cfba1 --- /dev/null +++ b/tests/fpc-websocket/WebSocketEagainRegression.lpr @@ -0,0 +1,430 @@ +program WebSocketEagainRegression; + +{ ============================================================================ + FIX-WS-NONBLOCK / FIX-WS-EINTR — regression test on the FPC + epoll path. + + Requested in review of HashLoad/horse PR #549. Horse's own suite is DUnitX + and Delphi-only (no .lpr, and Tests.Integration.WebSocket.pas carries no FPC + guards), so the FPC+epoll path cannot be covered there. This is a standalone + program instead: it starts a real epoll-backed Horse server, drives it with a + raw client socket, and asserts the four behaviours named in the review. + + THE DEFECT under test + --------------------- + epoll sets O_NONBLOCK on every accepted fd (Horse.Provider.Epoll.pas). On a + non-blocking socket recv returns -1/EAGAIN to mean "nothing yet" — the normal + state of an idle WebSocket peer. The transport's read loop treated every + non-positive result as a disconnect, so it broke on its FIRST iteration, + roughly a millisecond after the 101, before any frame could arrive. The + handler returned, the HTTP pipeline resumed, and a stray "HTTP/1.1 200 OK" + was written onto a socket already handed to WebSocket. + + WHAT EACH CHECK PROVES + ---------------------- + 1 first EAGAIN does not close immediately after the 101 the server is + SILENT. Pre-fix the loop broke here, the + handler returned, and the HTTP pipeline + wrote a stray 200 onto the socket. + 2 an idle connection stays open still silent after >4 read ticks (250 ms + each) — proves the loop parks in select() + rather than treating a timeout as a + disconnect. + 3 a later frame reaches OnMessage a frame sent AFTER that idle period is + echoed — the connection was not merely + intact but still functional. + 4 peer close releases the loop after an abrupt client close the server + still serves HTTP on the same port, + proving the read loop exited instead of + spinning or hanging. + + WHY CHECKS 1 AND 2 ASSERT SILENCE, NOT "STILL OPEN" + --------------------------------------------------- + This was got wrong once and the control run caught it. The first version of + this test asked "is the socket still open?" — and PASSED against the broken + transport, because the defect does not close the socket. It hands the socket + back to the HTTP pipeline, which writes an unsolicited "HTTP/1.1 200 OK". + The connection is open; it is just talking the wrong protocol. + + A correct server sends nothing at all between the 101 and the client's first + frame, so silence is the property that actually separates the two builds. + + Verified against upstream/master (pre-fix) with this exact program: + checks 1 and 2 report UNSOLICITED BYTES, check 3 fails with ~102 bytes of + HTTP where an echo was expected. + + BUILD AND RUN (Linux, FPC 3.2.2 or trunk) + ----------------------------------------- + mkdir -p /tmp/ws-out + fpc -MDelphi -B -dHORSE_PROVIDER_EPOLL \ + -Fu/src -Fi/src \ + -FU/tmp/ws-out -FE/tmp/ws-out \ + WebSocketEagainRegression.lpr + /tmp/ws-out/WebSocketEagainRegression + + -Fi is required as well as -Fu: Horse.Core.Param.Header.pas includes + Horse.FPC.inc, and an include path is not implied by the unit path. + + -B forces a full rebuild. A cached .ppu of the transport would silently test + the previous version of the very unit under test. + + TO RUN THE CONTROL (confirm the test still discriminates) + -------------------------------------------------------- + Point -Fu at a copy of src whose Horse.Provider.Socket.WebSocket.pas is the + pre-fix version; checks 1-3 must fail. A test that has never been observed + failing has not earned its place -- and the first draft of this one passed + 4 of 5 against the broken transport. + + Exit code = number of failed checks, so it can gate CI. + ============================================================================ } + +{$MODE DELPHI}{$H+} +{$DEFINE HORSE_PROVIDER_EPOLL} + +uses + {$IFDEF UNIX} + cthreads, { must precede every other unit on FPC/Unix — installs the + pthreads driver before anything can touch TThread } + {$ENDIF} + SysUtils, + Classes, + Sockets, + BaseUnix, + Horse, + Horse.Core.WebSocket; + +const + TEST_PORT = 9114; + READ_TICK_MS = 250; { WS_SOCKET_READ_TICK_MS in the transport } + IDLE_WAIT_MS = 1200; { > 4 ticks, so several EAGAIN→select cycles elapse } + SETTLE_MS = 120; { after the 101, before probing liveness } + +var + GPass: Integer = 0; + GFail: Integer = 0; + +procedure Check(const AName: string; const APassed: Boolean; const ADetail: string = ''); +begin + if APassed then + begin + Inc(GPass); + WriteLn(' PASS ', AName); + end + else + begin + Inc(GFail); + if ADetail <> '' then + WriteLn(' FAIL ', AName, ' [', ADetail, ']') + else + WriteLn(' FAIL ', AName); + end; +end; + +{ ── Server ───────────────────────────────────────────────────────────────── + PLAIN unit-scope procedures — not anonymous procedures and not class + procedures. + + FPC without FUNCTIONREFERENCES cannot bind a closure to THorseCallback, and + a class procedure does not satisfy it either: THorseCallback and + IHorseWebSocketConnection.OnMessage are plain procedure variable types, not + "of object" method pointers. FPC rejects a class procedure with + + Incompatible type for arg no. 1: Got "TWs.class OnMessage(...)", + expected "" + + which is the compiler distinguishing a method pointer (code + Self) from a + bare code pointer. Plain procedures are the only form that binds on FPC. } + +procedure WsOnMessage(const AConnection: IHorseWebSocketConnection; + const AText: string); +begin + { try/except per the WebSocket skill: an exception escaping here would kill + the worker socket thread. } + try + AConnection.SendText('echo:' + AText); + except + // swallow — a failed echo surfaces as a failed check, not a dead thread + end; +end; + +procedure WsOnConnect(const AConn: IHorseWebSocketConnection); +begin + AConn.OnMessage := WsOnMessage; +end; + +procedure RouteWS(Req: THorseRequest; Res: THorseResponse); +begin + Res.UpgradeToWebSocket(WsOnConnect); +end; + +procedure RoutePing(Req: THorseRequest; Res: THorseResponse); +begin + Res.Send('pong'); +end; + +type + TServerThread = class(TThread) + protected + procedure Execute; override; + end; + +procedure TServerThread.Execute; +begin + THorse.Listen(TEST_PORT); +end; + +{ ── Raw client helpers ───────────────────────────────────────────────────── + Deliberately no HTTP/WebSocket client library: the defect lives in how the + server reacts to silence, so the test must control exactly when bytes are + sent — including sending none at all. } + +function ConnectClient: LongInt; +var + LAddr: TInetSockAddr; +begin + Result := fpSocket(AF_INET, SOCK_STREAM, 0); + if Result < 0 then Exit; + FillChar(LAddr, SizeOf(LAddr), 0); + LAddr.sin_family := AF_INET; + LAddr.sin_port := htons(TEST_PORT); + LAddr.sin_addr := StrToNetAddr('127.0.0.1'); + if fpConnect(Result, @LAddr, SizeOf(LAddr)) <> 0 then + begin + fpClose(Result); + Result := -1; + end; +end; + +procedure SendStr(ASock: LongInt; const AText: string); +begin + if Length(AText) > 0 then + fpSend(ASock, @AText[1], Length(AText), 0); +end; + +{ Waits up to ATimeoutMS for readability. Returns True when the socket became + readable, False on timeout. } +function WaitReadable(ASock: LongInt; ATimeoutMS: Integer): Boolean; +var + LSet: TFDSet; + LTv: TTimeVal; +begin + fpFD_ZERO(LSet); + fpFD_SET(ASock, LSet); + LTv.tv_sec := ATimeoutMS div 1000; + LTv.tv_usec := (ATimeoutMS mod 1000) * 1000; + Result := fpSelect(ASock + 1, @LSet, nil, nil, @LTv) > 0; +end; + +function ReadAvailable(ASock: LongInt; ATimeoutMS: Integer): string; +var + LBuf: array[0..4095] of Byte; + LN: LongInt; +begin + Result := ''; + if not WaitReadable(ASock, ATimeoutMS) then Exit; + LN := fpRecv(ASock, @LBuf[0], SizeOf(LBuf), 0); + if LN > 0 then + begin + SetLength(Result, LN); + Move(LBuf[0], Result[1], LN); + end; +end; + +{ Post-upgrade quiet probe. Does not consume data (MSG_PEEK), so a later check + can still read whatever arrives. + + Returns: 0 silent and open — CORRECT: the server is parked in select() + 1 peer closed + 2 unsolicited bytes — THE DEFECT + -1 error + + Why "silent" and not "open" is the assertion + -------------------------------------------- + The obvious probe — "is the socket still open?" — does NOT detect this bug, + and an earlier version of this test wrongly passed against the broken + transport because of it. + + When the read loop breaks on its first EAGAIN, the upgrade handler returns + and the ordinary HTTP pipeline resumes on a socket that has already been + handed to WebSocket. It writes a stray "HTTP/1.1 200 OK ..." response. The + socket is therefore NOT closed — it is open with unexpected HTTP bytes in it, + so any "still open" check reports success against the very build it is meant + to catch. + + A correct server sends NOTHING between the 101 and the client's first frame. + Anything arriving in that window is the pipeline resuming, which is precisely + the failure. Hence: assert silence. } +function ProbeQuiet(ASock: LongInt; ATimeoutMS: Integer; out AData: string): Integer; +var + LBuf: array[0..1023] of Byte; + LN: LongInt; +begin + AData := ''; + if not WaitReadable(ASock, ATimeoutMS) then + Exit(0); { nothing readable → silent, as it should be } + LN := fpRecv(ASock, @LBuf[0], SizeOf(LBuf), MSG_PEEK); + if LN = 0 then + Result := 1 { orderly shutdown } + else if LN > 0 then + begin + SetLength(AData, LN); + Move(LBuf[0], AData[1], LN); + Result := 2; { unsolicited — the stray HTTP response } + end + else if (fpgeterrno = ESysEAGAIN) or (fpgeterrno = ESysEWOULDBLOCK) then + Result := 0 + else + Result := -1; +end; + +function ProbeName(AStatus: Integer): string; +begin + case AStatus of + 0: Result := 'silent+open'; + 1: Result := 'peer closed'; + 2: Result := 'UNSOLICITED BYTES'; + else Result := 'error'; + end; +end; + +{ A masked single-frame text message. Clients MUST mask (RFC 6455 §5.3). } +function BuildMaskedTextFrame(const AText: string): TBytes; +var + I, LLen: Integer; + LMask: array[0..3] of Byte; +begin + { Initialise before the guard: FPC warns that a managed result may be + unassigned on the raise path. } + Result := nil; + LLen := Length(AText); + if LLen > 125 then + raise Exception.Create('test helper only builds short frames'); + SetLength(Result, 6 + LLen); + LMask[0] := 1; LMask[1] := 2; LMask[2] := 3; LMask[3] := 4; + Result[0] := $81; { FIN + text opcode } + Result[1] := Byte($80 or LLen); { MASK + length } + for I := 0 to 3 do + Result[2 + I] := LMask[I]; + for I := 1 to LLen do + Result[5 + I] := Byte(Ord(AText[I])) xor LMask[(I - 1) mod 4]; +end; + +function DoHandshake(ASock: LongInt): string; +begin + SendStr(ASock, + 'GET /ws HTTP/1.1'#13#10 + + 'Host: 127.0.0.1:' + IntToStr(TEST_PORT) + #13#10 + + 'Upgrade: websocket'#13#10 + + 'Connection: Upgrade'#13#10 + + 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ=='#13#10 + + 'Sec-WebSocket-Version: 13'#13#10#13#10); + Result := ReadAvailable(ASock, 5000); +end; + +{ ── Checks ─────────────────────────────────────────────────────────────── } + +procedure RunChecks; +var + LSock: LongInt; + LResp: string; + LFrame: TBytes; + LEcho: string; + LSeen: string; + LOpen: Integer; +begin + WriteLn; + WriteLn('── 1 first EAGAIN must not close the connection ──────────────'); + LSock := ConnectClient; + if LSock < 0 then + begin + Check('connect to server', False, 'socket/connect failed'); + Exit; + end; + + LResp := DoHandshake(LSock); + Check('handshake returns 101 Switching Protocols', + Pos('101', LResp) > 0, Copy(LResp, 1, 60)); + + { The server's read loop has now issued at least one recv and taken EAGAIN. + Pre-fix the loop broke here, the handler returned, and the HTTP pipeline + wrote a stray 200 onto the upgraded socket — which is what this detects. } + Sleep(SETTLE_MS); + LOpen := ProbeQuiet(LSock, 150, LSeen); + Check('server silent after the first EAGAIN (no stray HTTP response)', + LOpen = 0, + ProbeName(LOpen) + ' :: ' + Copy(LSeen, 1, 48)); + + WriteLn; + WriteLn('── 2 an idle connection stays open ───────────────────────────'); + Sleep(IDLE_WAIT_MS); { > 4 read ticks — several select() timeouts elapse } + LOpen := ProbeQuiet(LSock, 150, LSeen); + Check('still silent and open after ' + IntToStr(IDLE_WAIT_MS) + ' ms idle', + LOpen = 0, + ProbeName(LOpen) + ' :: ' + Copy(LSeen, 1, 48)); + + WriteLn; + WriteLn('── 3 a frame sent later reaches OnMessage ────────────────────'); + LFrame := BuildMaskedTextFrame('ping-after-idle'); + fpSend(LSock, @LFrame[0], Length(LFrame), 0); + LEcho := ReadAvailable(LSock, 5000); + Check('echo received for a frame sent after the idle period', + Pos('echo:ping-after-idle', LEcho) > 0, + 'bytes=' + IntToStr(Length(LEcho))); + + WriteLn; + WriteLn('── 4 peer close releases the read loop ───────────────────────'); + { Abrupt close, no WebSocket close frame — the harsher case. } + fpClose(LSock); + Sleep(READ_TICK_MS * 3); { give the loop more than one tick to notice } + + LSock := ConnectClient; + if LSock < 0 then + Check('server still accepts connections after peer close', False, 'connect failed') + else + begin + SendStr(LSock, + 'GET /ping HTTP/1.1'#13#10 + + 'Host: 127.0.0.1:' + IntToStr(TEST_PORT) + #13#10 + + 'Connection: close'#13#10#13#10); + LResp := ReadAvailable(LSock, 5000); + Check('server still serves HTTP after an abrupt peer close', + (Pos('200', LResp) > 0) and (Pos('pong', LResp) > 0), + Copy(LResp, 1, 60)); + fpClose(LSock); + end; +end; + +var + LServer: TServerThread; +begin + WriteLn('FIX-WS-NONBLOCK / FIX-WS-EINTR regression — FPC + epoll'); + WriteLn('Port: ', TEST_PORT); + + THorse.Get('/ws', RouteWS); + THorse.Get('/ping', RoutePing); + + LServer := TServerThread.Create(False); + try + Sleep(700); { let the listener bind before the first connect } + try + RunChecks; + except + on E: Exception do + Check('unexpected exception', False, E.ClassName + ': ' + E.Message); + end; + finally + try + THorse.StopListen; + except + end; + LServer.WaitFor; + LServer.Free; + end; + + WriteLn; + WriteLn(Format('%d passed, %d failed', [GPass, GFail])); + if GFail = 0 then + WriteLn('All checks PASSED.') + else + WriteLn('Some checks FAILED — see above.'); + ExitCode := GFail; +end. diff --git a/tests/fpc-websocket/run-ws-eagain-test.sh b/tests/fpc-websocket/run-ws-eagain-test.sh new file mode 100755 index 00000000..fbfa9f1c --- /dev/null +++ b/tests/fpc-websocket/run-ws-eagain-test.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# ============================================================================= +# FIX-WS-NONBLOCK / FIX-WS-EINTR regression — build + run on FPC + epoll. +# +# Requested in review of HashLoad/horse PR #549. Horse's own suite is DUnitX +# and Delphi-only, so the FPC+epoll path needs a standalone program; this +# builds and runs it. +# +# HORSE_SRC=/path/to/horse/src ./run-ws-eagain-test.sh +# +# Exit code = number of failed checks, so it can gate CI directly. +# ============================================================================= +set -uo pipefail + +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +HORSE_SRC=${HORSE_SRC:-$(cd "$HERE/../../src" 2>/dev/null && pwd)} +FPC=${FPC:-fpc} +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +echo "FPC : $($FPC -iV 2>/dev/null || echo 'NOT FOUND')" +echo "Horse src : $HORSE_SRC" + +if ! command -v "$FPC" >/dev/null 2>&1; then + echo "FAIL: fpc not on PATH. Set FPC=/path/to/fpc." >&2 + exit 1 +fi + +if [[ ! -f "$HORSE_SRC/Horse.pas" ]]; then + echo "FAIL: Horse.pas not found under $HORSE_SRC" >&2 + echo " Set HORSE_SRC to the horse/src directory." >&2 + exit 1 +fi + +# The guard this test exists to protect. Without it the run is meaningless — +# every check would fail for the same reason and prove nothing about the loop. +if ! grep -q 'WS_SOCKET_READ_TICK_MS' "$HORSE_SRC/Horse.Provider.Socket.WebSocket.pas" 2>/dev/null; then + echo "FAIL: $HORSE_SRC/Horse.Provider.Socket.WebSocket.pas is missing FIX-WS-NONBLOCK." >&2 + echo " This tree predates the fix; the test would fail for the wrong reason." >&2 + exit 1 +fi + +echo +echo "── compiling ──────────────────────────────────────────────────────────" +# -B forces a full rebuild: a cached .ppu of the transport would silently test +# the previous version of the very unit under test. +if ! "$FPC" -MDelphi -B -O1 -gl \ + -dHORSE_PROVIDER_EPOLL \ + -Fu"$HORSE_SRC" \ + -Fu"$HORSE_SRC/Providers" \ + -FU"$WORK" -FE"$WORK" \ + "$HERE/WebSocketEagainRegression.lpr" > "$WORK/build.log" 2>&1; then + echo "FAIL: compilation failed" + tail -30 "$WORK/build.log" | sed 's/^/ | /' + exit 1 +fi +echo " compiled OK" + +echo +echo "── running ────────────────────────────────────────────────────────────" +"$WORK/WebSocketEagainRegression" +RC=$? + +echo +if [[ $RC -eq 0 ]]; then + echo "RESULT: all checks passed" +else + echo "RESULT: $RC check(s) failed" +fi +exit $RC From bf6f236220a8f10c45775f4f2ae7b34604fee3b6 Mon Sep 17 00:00:00 2001 From: freitasjca Date: Sat, 5 Sep 2026 20:38:04 +0100 Subject: [PATCH 09/11] fix(tests): restore the WebSocket epoll regression step in the Lazarus image Our version of Dockerfile.tests-lazarus deleted upstream's WebSocketEpollRegression build-and-run step and replaced it with a build of FPCHttpKeepaliveTest, so the Lazarus test image silently stopped covering the non-blocking WebSocket transport. The replacement comment also restated the disproved cause of the keep-alive stall - a fixed ~40 ms select() poll interval - superseded by the Nagle/delayed-ACK finding in horse#562. Reverted to upstream's version outright rather than patched, because the rest of our change is no longer wanted either: fp-units-web was added only for that keep-alive build step, and nothing else in the image uses fphttpclient. This file is now byte-identical to upstream, which is one less thing to reconcile at the next sync. The keep-alive test is deliberately NOT re-added here. It now refuses to build below FPC 3.3.1, where the provider's keep-alive and TCP_NODELAY code is not compiled at all, and this image installs Ubuntu 22.04's fpc 3.2.2 - so adding it would fail the image build. It runs standalone against trunk instead. --- tests/Dockerfile.tests-lazarus | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/tests/Dockerfile.tests-lazarus b/tests/Dockerfile.tests-lazarus index e6c43987..d2a3df9b 100644 --- a/tests/Dockerfile.tests-lazarus +++ b/tests/Dockerfile.tests-lazarus @@ -2,11 +2,11 @@ FROM ubuntu:22.04 ENV DEBIAN_FRONTEND=noninteractive -# fp-units-web provides fphttpclient and fphttpserver (needed by FPCHttp provider + test) RUN apt-get update && apt-get install -y \ - fpc fp-units-rtl fp-units-fcl fp-units-misc fp-units-web git ca-certificates \ + fpc fp-units-rtl fp-units-fcl fp-units-misc git ca-certificates \ && rm -rf /var/lib/apt/lists/* +# Clona o DUnitX não é mais necessário para o teste de integração simples WORKDIR /usr/src/app COPY . . @@ -15,15 +15,10 @@ COPY . . RUN mkdir -p tests/lib && cd tests/src && \ fpc -Mdelphi -Sh -FE.. -FU../lib -Fu"../../src:modules/jhonson/src:modules/restrequest4delphi/src:modules/cors/src:modules/basic-auth/src" "-dHORSE_CONSOLE" "-dHORSE_PROVIDER_EPOLL" IntegrationServer.dpr -# BENCH-FPCHTTP-1 regression test — FPCHttp provider with KeepConnections=False. -# Verifies that sequential HTTP requests complete in ≤35 ms each (the keepalive -# loop stall was exactly ~40 ms on every kernel tested). No HORSE_* define is -# needed: FPC selects Horse.Provider.FPC.HTTPApplication by default. -RUN mkdir -p tests/bench-fpchttp/lib && cd tests/src && \ - fpc -Mdelphi -Sh \ - -FE../bench-fpchttp -FU../bench-fpchttp/lib \ - -Fu"../../src:modules/horse/src" \ - FPCHttpKeepaliveTest.dpr +# Regressao do transporte WebSocket non-blocking usado pelo provider epoll. +RUN mkdir -p tests/lib-websocket && cd tests/src && \ + fpc -Mdelphi -Sh -FE.. -FU../lib-websocket -Fu"../../src" "-dHORSE_CONSOLE" "-dHORSE_PROVIDER_EPOLL" WebSocketEpollRegression.dpr && \ + ../WebSocketEpollRegression WORKDIR /usr/src/app/tests From 9e2849e7793e203ba41bcb34251452da9312a60d Mon Sep 17 00:00:00 2001 From: freitasjca Date: Sat, 3 Oct 2026 18:24:50 +0100 Subject: [PATCH 10/11] docs(readme): drop the duplicate horse-prometheus-metrics row left by a merge --- README.md | 1 - README.pt-BR.md | 1 - 2 files changed, 2 deletions(-) diff --git a/README.md b/README.md index cc13b4c2..87434f28 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,6 @@ This is a list of middlewares that are created by the Horse community, please cr | [isaquepinheiro/horse-jsonbr](https://github.com/HashLoad/JSONBr) |    ✔️ |     ❌ | | [IagooCesaar/Horse-JsonInterceptor](https://github.com/IagooCesaar/Horse-JsonInterceptor) |    ✔️ |     ❌ | | [dliocode/horse-datalogger](https://github.com/dliocode/horse-datalogger) |    ✔️ |     ❌ | -| [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | | [weslleycapelari/horse-documentation](https://github.com/weslleycapelari/horse-documentation) |    ✔️ |     ❌ | | [weslleycapelari/horse-validator](https://github.com/weslleycapelari/horse-validator) |    ✔️ |     ❌ | | [regyssilveira/horse-rate-limit](https://github.com/regyssilveira/horse-rate-limit) |    ✔️ |     ✔️ | diff --git a/README.pt-BR.md b/README.pt-BR.md index 51ebb725..9f0eb4ec 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -202,7 +202,6 @@ Esta é uma lista de middlewares criados pela comunidade Horse — abra um PR se | [isaquepinheiro/horse-jsonbr](https://github.com/HashLoad/JSONBr) |    ✔️ |     ❌ | | [IagooCesaar/Horse-JsonInterceptor](https://github.com/IagooCesaar/Horse-JsonInterceptor) |    ✔️ |     ❌ | | [dliocode/horse-datalogger](https://github.com/dliocode/horse-datalogger) |    ✔️ |     ❌ | -| [marcobreveglieri/horse-prometheus-metrics](https://github.com/marcobreveglieri/horse-prometheus-metrics) |    ✔️ |     ❌ | | [weslleycapelari/horse-documentation](https://github.com/weslleycapelari/horse-documentation) |    ✔️ |     ❌ | | [weslleycapelari/horse-validator](https://github.com/weslleycapelari/horse-validator) |    ✔️ |     ❌ | | [regyssilveira/horse-rate-limit](https://github.com/regyssilveira/horse-rate-limit) |    ✔️ |     ✔️ | From b67a9eaf6647b78c6adbddd83b6cdf9ec503c417 Mon Sep 17 00:00:00 2001 From: freitasjca Date: Mon, 2 Nov 2026 23:23:07 +0000 Subject: [PATCH 11/11] fix: guard HttpSys SendResponse against a nil custom-header dict The HTTP.sys provider access-violates when sending a response whose headers were set only via Res.RawWebResponse.SetCustomHeader with no Res.AddHeader call - exactly what Horse.CORS does. SendResponse's Delphi branch enumerates the shadow CustomHeaders dict (for LPair in LHeadersList), which is nil in that case, while the raw header count is > 0 so the block is still entered: EAccessViolation (Read of 0x00000004). The FPC branch above is already safe (for I := 0 to LHeaderCount - 1, which is 0 when the dict is nil). Fix: a one-line nil guard before the for..in. Regression test (samples/tests): new route /raw/setheader-only (SetCustomHeader only, no AddHeader - keeps the shadow dict nil) plus client Section 37. Negative control on the HTTP.sys test server: unfixed -> AV + Section 37 fails (101 passed / 2 failed) fixed -> 104 passed / 0 failed (sections 1-36 unaffected) The route is provider-agnostic and also passes on Indy / Epoll / IOCP. Files: src/Horse.Provider.HttpSys.pas samples/tests/Horse.Indy.TestRoutes.pas samples/tests/HorseNetHttpTestClient.dpr --- samples/tests/Horse.Indy.TestRoutes.pas | 26 ++++++++++++++++++++++++ samples/tests/HorseNetHttpTestClient.dpr | 14 +++++++++++++ src/Horse.Provider.HttpSys.pas | 5 +++++ 3 files changed, 45 insertions(+) diff --git a/samples/tests/Horse.Indy.TestRoutes.pas b/samples/tests/Horse.Indy.TestRoutes.pas index 371a51dd..de312eac 100644 --- a/samples/tests/Horse.Indy.TestRoutes.pas +++ b/samples/tests/Horse.Indy.TestRoutes.pas @@ -406,6 +406,32 @@ procedure RegisterTestRoutes; end ); + // ── FIX-HTTPSYS-CORS-NIL regression: header set ONLY via RawWebResponse ─── + // Reproduces the http.sys AV: when a response header arrives only through + // Res.RawWebResponse.SetCustomHeader and AddHeader is NEVER called (exactly + // what Horse.CORS does), the shadow CustomHeaders dict stays nil while the + // raw header count is > 0 — so THttpSysRawResponse.SendResponse's for..in + // enumerated a nil dict and AV'd. Provider-agnostic: Indy/Epoll/IOCP always + // passed; this route is the guard for HttpSys. + THorse.Get('/raw/setheader-only', + procedure(Req: THorseRequest; Res: THorseResponse) + var + LRaw: TRawWebRes; + begin + LRaw := Res.RawWebResponse; + if not Assigned(LRaw) then + begin + Res.ContentType('application/json; charset=utf-8').Status(500) + .Send('{"error":"RawWebResponse is nil"}'); + Exit; + end; + // Deliberately NO Res.AddHeader anywhere — the shadow header dict must + // remain nil so the HttpSys nil-enumeration path is exercised. + LRaw.SetCustomHeader('X-Raw-Only', 'raw-only-ok'); + Res.Send('raw-only-ok'); + end + ); + // ── PATCH-REQ-9: double-read idempotency ───────────────────────────────── THorse.Post('/echo/body-twice', procedure(Req: THorseRequest; Res: THorseResponse) diff --git a/samples/tests/HorseNetHttpTestClient.dpr b/samples/tests/HorseNetHttpTestClient.dpr index 77dacbf6..81697d8b 100644 --- a/samples/tests/HorseNetHttpTestClient.dpr +++ b/samples/tests/HorseNetHttpTestClient.dpr @@ -802,6 +802,20 @@ begin (R.StatusCode = 200) and (R.Body = 'pong'), Format('%d / %s', [R.StatusCode, R.Body])); + // ── 37 ───────────────────────────────────────────────────────────────────── + // FIX-HTTPSYS-CORS-NIL: a header set ONLY via RawWebResponse.SetCustomHeader + // (no AddHeader) must not AV the HttpSys provider. Pre-fix: http.sys + // SendResponse enumerated a nil shadow dict -> AV / dropped connection. + // Post-fix: 200 + header. Passes on every other provider too. + Section('37 GET /raw/setheader-only (FIX-HTTPSYS-CORS-NIL - SetCustomHeader, no AddHeader)'); + DoReq(LClient, 'GET', BASE_URL + '/raw/setheader-only', nil, nil, R); + Check('status 200', R.StatusCode = 200, IntToStr(R.StatusCode)); + Check('body = "raw-only-ok"', R.Body = 'raw-only-ok', R.Body); + if Assigned(R.Response) then + Check('X-Raw-Only: raw-only-ok', + R.Response.HeaderValue['X-Raw-Only'] = 'raw-only-ok', + R.Response.HeaderValue['X-Raw-Only']); + finally LClient.Free; end; diff --git a/src/Horse.Provider.HttpSys.pas b/src/Horse.Provider.HttpSys.pas index 47eb059e..9719dffb 100644 --- a/src/Horse.Provider.HttpSys.pas +++ b/src/Horse.Provider.HttpSys.pas @@ -1521,6 +1521,11 @@ procedure THttpSysRawResponse.SendResponse(const ARes: THorseResponse); Inc(LHdrIdx); end; {$ELSE} + // FIX-HTTPSYS-CORS-NIL: the shadow CustomHeaders dict is nil when headers arrived only via + // RawWebResponse (e.g. Horse.CORS calls Res.RawWebResponse.SetCustomHeader, never AddHeader), + // yet the block is entered because LRawHeaderCount/LRepeatCount > 0 — so guard the for..in. + // (The FPC branch above is already guarded by LHeaderCount, which is 0 when the dict is nil.) + if LHeadersList <> nil then for LPair in LHeadersList do if not SameText(LPair.Key, 'Set-Cookie') then begin