From aa27866531678bb979feaf4cc81f3f0c14812255 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Gruszczy=C5=84ski?= Date: Mon, 23 Nov 2026 11:07:13 +0100 Subject: [PATCH] v0.41.0 --- AGENTS.md | 2 +- CHANGELOG.md | 17 + Cargo.lock | 2 +- Cargo.toml | 2 +- docs/CUSTOM_LOCATIONS.md | 50 +- docs/FEATURES.md | 2 +- docs/HEADLESS.md | 4 +- docs/LOAD_BALANCING.md | 136 ++++++ docs/README.md | 3 +- docs/VHOSTS.md | 4 +- langs/en_US.json | 107 ++++- langs/pl_pl.json | 107 ++++- src/admin/documentation/documents.rs | 1 + src/admin/openapi.json | 187 +++++++- src/admin/router.rs | 2 + src/admin/web/css/40-editors.css | 248 +++++++++- src/admin/web/css/70-responsive.css | 12 + src/admin/web/vhosts/balancing.js | 255 +++++++++++ src/admin/web/vhosts/core.js | 95 +++- src/admin/web/vhosts/editor.js | 5 +- src/admin/web/vhosts/routing.js | 227 ++++++++++ src/balance.rs | 2 + src/balance/hash_tests.rs | 426 ++++++++++++++++++ src/balance/health.rs | 8 + src/balance/model.rs | 255 +++++++++++ src/balance/pool_core.rs | 382 +++++++++++----- src/balance/pool_selection.rs | 45 +- src/config.rs | 2 + src/config/model.rs | 7 + src/config/routing.rs | 67 ++- src/config/routing_conditions_tests.rs | 159 +++++++ src/config/snapshot.rs | 97 ++-- src/proxy/body/mod.rs | 3 + src/proxy/body/tests.rs | 1 + src/proxy/forward/route_cache.rs | 2 +- src/proxy/forward/upstream.rs | 3 +- src/proxy/forward_entry.rs | 36 +- src/proxy/upstream_helpers.rs | 7 + src/vhost.rs | 1 + src/vhost/conditions.rs | 351 +++++++++++++++ src/vhost/model.rs | 13 + src/vhost/validation.rs | 71 ++- tests/fixtures/balance_rendezvous_vectors.txt | 1 + tests/fixtures/routing_conditions_cases.json | 55 +++ tools/dev/test_balance_simulator.js | 60 +++ tools/dev/test_routing_tester.js | 35 ++ 46 files changed, 3368 insertions(+), 189 deletions(-) create mode 100644 docs/LOAD_BALANCING.md create mode 100644 src/admin/web/vhosts/balancing.js create mode 100644 src/admin/web/vhosts/routing.js create mode 100644 src/balance/hash_tests.rs create mode 100644 src/config/routing_conditions_tests.rs create mode 100644 src/vhost/conditions.rs create mode 100644 tests/fixtures/balance_rendezvous_vectors.txt create mode 100644 tests/fixtures/routing_conditions_cases.json create mode 100644 tools/dev/test_balance_simulator.js create mode 100644 tools/dev/test_routing_tester.js diff --git a/AGENTS.md b/AGENTS.md index d33bb42..bd32cfc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # RustProxy source and documentation maintenance -Current source version: **0.40.1**. The Cargo package and binary are named `rust-proxy`. +Current source version: **0.41.0**. The Cargo package and binary are named `rust-proxy`. Before editing, read [README.md](README.md), the relevant [documentation guide](docs/README.md) and the actual code and tests. Historical release experiments are not current specifications. Use the bundled `src/admin/openapi.json` for API routes and payloads; the source implementation is authoritative for runtime behavior. diff --git a/CHANGELOG.md b/CHANGELOG.md index 474d571..dc2cd3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ Release history focused on **features, settings, default behavior, compatibility and fixes**. Changes to internal code structure and preliminary performance experiments are intentionally omitted. Historical descriptions reflect their respective releases; consult the current documentation for the settings available in the latest release. +## 0.41.0 — Conditional routing: request conditions and whole-host rules + +- **Location conditions (HAProxy `use_backend … if ` style):** a custom location accepts `conditions` — up to 16 tests on `header`, `cookie`, `query` (parameter), `method`, `ip` (client address after trusted forwarding/Cloudflare, `cidr` with IPs or networks), `host` or `country` (GeoIP/Cloudflare), with the operators `equals`, `exists`, `prefix`, `suffix`, `contains`, `regex` and `cidr`, `negate` and `ignore_case`. All conditions must hold (AND); a condition matches when any of its values matches (OR). A location whose conditions fail is skipped and the next candidate is used, so `/api/` + `X-Beta: 1` → beta backends can sit next to a plain `/api/`. For exact paths and prefixes of equal length the conditional location wins; regular expressions are tried in list order, and a conditional regex placed after an identical unconditional one is rejected as unreachable. See [Request conditions](docs/CUSTOM_LOCATIONS.md#request-conditions-routing-by-header-cookie-ip). +- **Rules for the whole host:** the new match type `any` (requires at least one condition) applies to every path of the Vhost and ranks like a regular expression — e.g. office network + staff cookie → `office` backends for the whole site. Combined with the 0.40.2 backend groups and per-location balancing this covers frontend-level and path-level `use_backend` rules. +- **Correctness and caching:** conditional locations are selected after the final client address and (when a condition needs it) the country are known; earlier stages and proactive cache refreshes only consider unconditional locations, and the response layer uses the finally selected location. Responses of conditional locations are never cached (`cache` must be inherit/off), so a cached unconditional response is never served to a request that matches a conditional location. +- **Panel:** each location has a **Conditions** section (source, name, operator, values one per line, NOT, ignore case), an **Add rule for the whole host** button, **↑ / ↓** buttons to order locations, condition counts in the summary and a **Test routing** panel that evaluates the unsaved draft: method, URL, client IP, country and headers → winning location, path ✓/✗ and every condition ✓/✗ for all locations, the target backend (including the consistent-hash member) and the cache bypass. English and Polish texts added. +- **Compatibility:** configurations without `conditions` or `match_type: "any"` are unchanged and serialize as before. Configurations using them are rejected by 0.40.2 and older. Glob wildcards are still not supported in paths; use regular expressions (documented). +- **Verification:** new Rust tests run 19 shared routing cases from `tests/fixtures/routing_conditions_cases.json` (exact/prefix/regex/any precedence, fall-through, every source and operator, negation, country, IPv4/IPv6 CIDR), check that conditional locations are skipped without request facts and never cached, and reject 14 invalid configurations; `tools/dev/test_routing_tester.js` runs the same cases against the panel tester. Full suite, `cargo clippy --all-targets` and `cargo fmt --check` clean. The real binary was run in headless mode against four mock origins: header, IP + cookie (whole-host rule) and POST-only routing reached the expected origins; a cacheable `/api/` response was `HIT` for plain requests while `X-Beta` requests went to the beta origin with `BYPASS / route_disabled`. In panel mode (Chrome) the tester, a new whole-host rule, reordering and saving were exercised. Not tested: production traffic, HTTP/3 clients, GeoIP-based country conditions with a real database. + +## 0.40.2 — Consistent-hash balancing and per-location backend groups + +- **New algorithms:** `hash` — consistent (weighted rendezvous) hash of a request key — and `random` (power of two random choices). The `hash` key is set in `load_balancing.hash`: `source` = `path` (default, path as received, before location rewrites), `uri` (path + query), `host`, `header`, `cookie`, `query` (one parameter) or `ip`; `name` for header/cookie/query; `path_depth` (hash only the first N directories); `ignore_case`; `balance_factor` (bounded load, 101–1000 %, like HAProxy `hash-balance-factor`); `fallback` algorithm for requests without the key (default `round_robin`). Hashing is always consistent: a failed, drained or removed member only moves its own keys, which return when it recovers; weights scale each member's share of keys. See [Load balancing](docs/LOAD_BALANCING.md). +- **Location backend groups (HAProxy `use_backend` style):** a Proxy location accepts `backend_ids` (a group of Vhost backends, up to 64) and `load_balancing` (`algorithm`, `hash`, `sticky`) to balance its requests differently from the rest of the Vhost — for example `\.mp3$` → `mp3_1..3` hashed by path while `/` stays on least connections. Members are shared with the Vhost pool (health, passive ejection, drain, concurrency limits, statistics), retries stay inside the group, and backends with `pool_eligible: false` serve only the locations that list them. A location affinity cookie is named `__`; the Vhost and its locations strip each other's affinity cookies before forwarding. +- **Panel:** the Vhost **Balancing** section and a new **Backends & balancing** section per location offer the new algorithms with a one-line explanation each, *Quick setup* buttons (files by path, session cookie, tenant header, query parameter, client IP, even load), the equivalent HAProxy lines, a backend-group picker and **Test distribution** — an in-browser simulator on the unsaved draft that shows the hash key and backend per sample, the share per backend and which keys move when a backend is marked as failed. It ranks backends with the same SHA-256 rendezvous scoring as the proxy (`tools/dev/test_balance_simulator.js` checks it against the Rust reference vectors). English and Polish texts added. +- **Compatibility:** configurations without the new fields are unchanged and still serialize without them; `ip_hash` keeps the same client → backend mapping. Configurations using `hash`, `random`, `backend_ids` or location `load_balancing` are rejected by 0.40.1 and older. `backend_id` (pinned backend) cannot be combined with a group or location balancing. OpenAPI, Vhost/location/headless guides and the feature list updated. +- **Verification:** 14 new unit tests (key extraction for every source, validation, stability, even spread, weight shares, only-the-failed-member's-keys move, fallback, bounded load, random, unchanged `ip_hash` mapping, location group compilation with shared member state, affinity cookie stripping, invalid groups) and the Node simulator test; full suite (1043 library tests, 7 CLI tests), `cargo clippy --all-targets` and `cargo fmt --check` clean. The real binary was run in headless mode with the `.mp3` example above against four mock origins: 61 paths were spread over `mp3_1..3` and stayed stable over repeated requests, `/` stayed on `app`, a header-hashed location kept tenants stable and used round robin without the header; stopping `mp3_2` moved exactly its 27 keys (all others stayed), and after it came back every key returned to its original backend. In panel mode (Chrome) the editors, presets, simulator and failure simulation were used on a saved Vhost and a new location group was created and saved through the UI. Not tested: production traffic, HTTP/3 clients and multi-node deployments. + ## 0.40.1 — Forced certificate renewal (panel and headless) - **Panel — Force renewal now:** each managed ACME certificate in **Certificates → Automatic renewal** has a new action next to *Check now* and *Validate renewal (dry run)*. It runs `certbot renew --force-renewal` for that profile, so a new certificate is requested even if the current one is not due (key compromise, CA revocation, chain change). A confirmation explains the CA rate limits; the current certificate stays active until the new pair is validated and deployed. The job kind is `renewal-forced`, the audit action `acme.renew_forced`; if Certbot returns the installed pair unchanged the result is `acme.force_unchanged`. diff --git a/Cargo.lock b/Cargo.lock index 7913ccc..bec3ec4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ dependencies = [ [[package]] name = "rust-proxy" -version = "0.40.1" +version = "0.41.0" dependencies = [ "anyhow", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index 75ff804..251f4e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-proxy" -version = "0.40.1" +version = "0.41.0" edition = "2021" rust-version = "1.99.1" description = "RustProxy - independent reverse proxy with local administration" diff --git a/docs/CUSTOM_LOCATIONS.md b/docs/CUSTOM_LOCATIONS.md index 4874202..51de880 100644 --- a/docs/CUSTOM_LOCATIONS.md +++ b/docs/CUSTOM_LOCATIONS.md @@ -10,12 +10,60 @@ Custom locations add exceptions to a Vhost's normal source. They are **not** req | `prefix_priority` | Longest prefix that suppresses regex evaluation | Ahead of regex when matched | | `regex` / `regex_insensitive` | Case-sensitive or insensitive regular expression | Tested in configured order after priority-prefix rules | | `prefix` | Ordinary longest matching path prefix | Fallback among matching rules | +| `any` | Every path — a rule for the whole host, selected only by its conditions | Same as regex: configured order, after priority-prefix rules | + +Glob wildcards (`*.mp3`) are not supported; use a regular expression such as `\.mp3$`. Regular expressions use the Rust `regex` syntax (no look-around or back-references). Encoded `/` separators (`%2F` / `%2f`) are normalized to real `/` only for location matching and security policy. Other ambiguous or unsafe encoded path forms remain rejected. In `preserve` rewrite mode the original encoded request target is forwarded unchanged to the upstream, so `/a%2Fb?x=1` is matched as `/a/b` but reaches the backend as `/a%2Fb?x=1`. Rewritten modes generate a new normalized target instead. Avoid overlapping regex rules when order matters; test paths with and without trailing `/`. +## Request conditions (routing by header, cookie, IP…) + +A location can require extra **conditions** besides its path — the RustProxy equivalent of HAProxy ACLs in `use_backend if `. Each condition tests one request attribute: + +| `source` | `name` | Operators | Notes | +|---|---|---|---| +| `header` | header name | `equals`, `exists`, `prefix`, `suffix`, `contains`, `regex` | Repeated header lines are tested one by one. | +| `cookie` | cookie name | same as header | | +| `query` | parameter name | same as header | Raw (not URL-decoded) value. | +| `method` | — | `equals` | `GET`, `POST`… (case-insensitive). | +| `ip` | — | `cidr` | Client address after trusted forwarding / Cloudflare handling; values are IPs or networks (`10.0.0.0/8`, `2001:db8::/32`). | +| `host` | — | `equals`, `prefix`, `suffix`, `contains`, `regex` | Host name without port, lower-case; useful with wildcard Vhosts. | +| `country` | — | `equals` | ISO codes from the GeoIP database or Cloudflare (`PL`, `DE`). | + +Rules: **all conditions of a location must hold (AND)**; a condition matches when **any of its `values`** matches (OR); `negate` inverts one condition; `ignore_case` makes header, cookie and query comparisons case-insensitive. For an OR between whole rules add several locations. Up to 16 conditions per location and 64 values per condition. + +Selection with conditions: + +1. A location whose conditions fail is **skipped** and the next candidate is tried — so `/api/` with `X-Beta: 1` and a plain `/api/` can coexist, and the request falls through to the plain one without the header. +2. For exact paths and for prefixes of equal length a location with conditions is preferred over one without; regular expressions and `any` rules are tried **in list order** (move rules with **↑ / ↓** in the panel). A conditional regex placed after an identical unconditional one would never match and is rejected. +3. **Rule for the whole host:** match type `any` (panel: *Add rule for the whole host*) applies to every path, like a frontend-level `use_backend … if …`. It needs at least one condition and ranks like a regular expression: exact paths and priority prefixes still win, ordinary prefixes lose. +4. Responses of locations with conditions are **never cached** (their content depends on request attributes outside the cache key), and `cache` must be inherit or off. Unconditional locations and the main source cache as before. +5. Internal (error-fallback) locations cannot have conditions. + +Example — beta testers by header, office network with a staff cookie for the whole host, `.mp3` files for EU visitors: + +```json +"routes": [ + { "id": "api-beta", "path_prefix": "/api/", "backend_ids": ["beta"], + "conditions": [{ "source": "header", "name": "X-Beta", "values": ["1"] }] }, + { "id": "api", "path_prefix": "/api/" }, + { "id": "office", "match_type": "any", "backend_ids": ["office"], + "conditions": [ + { "source": "ip", "operator": "cidr", "values": ["10.0.0.0/8"] }, + { "source": "cookie", "name": "staff", "operator": "exists" } ] }, + { "id": "mp3-eu", "match_type": "regex_insensitive", "path_prefix": "\\.mp3$", + "backend_ids": ["mp3_eu_1", "mp3_eu_2"], "load_balancing": { "algorithm": "hash" }, + "conditions": [{ "source": "country", "values": ["PL", "DE", "FR"] }] } +] +``` + +### Routing tester + +**Vhosts → Edit → Custom locations → Test routing** evaluates the unsaved draft in the browser: enter a method, URL, client IP, country and headers (cookies as a `Cookie:` header) to see which location wins, why every other location was skipped (path ✓/✗ and each condition ✓/✗), the backend or hash target and whether the cache is bypassed. Its matching logic is checked against the proxy with the shared cases in `tests/fixtures/routing_conditions_cases.json` (`tools/dev/test_routing_tester.js`). Regular expressions are run by the browser engine, which covers the common syntax; the server always validates the saved configuration. + ## Actions -- **Proxy:** use the Vhost backend pool or target a specific backend. A location can have an explicit cache override. +- **Proxy:** use the Vhost backend pool, a **backend group** (`backend_ids`) or one specific backend. The pool or group can use its own algorithm, hash key and affinity (`load_balancing`), for example a consistent hash of the path for `.mp3` files only — see [Load balancing](LOAD_BALANCING.md#location-backend-groups). A location can have an explicit cache override. - **Web Server:** reference an existing Web Service with its saved document root and PHP/static settings. - **Local response:** return a chosen `200–599` status, content type and body without connecting to an origin. `HEAD`, `204` and `304` do not return a body. - **Redirect:** issue `301`, `302`, `303`, `307` or `308` to a valid absolute HTTP(S) target. Query preservation is configurable. Redirect rewrite expressions may reference regex captures. diff --git a/docs/FEATURES.md b/docs/FEATURES.md index bb3485a..16b47b1 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -10,7 +10,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se |---|---| | Vhosts | Exact and wildcard hostnames, aliases, several listeners per Vhost, per-Vhost HTTP/2 and HTTP/3 switches | | Backends | HTTP and HTTPS origins, HTTP/1.1, automatic ALPN (H2/H1), strict HTTP/2 and H2C, optional upstream certificate verification with custom CA and server name | -| Load balancing | Least connections (default), round robin, least traffic, adaptive and IP hash; member weights, backup and draining members, sticky cookie or IP affinity | +| Load balancing | Least connections (default), round robin, least traffic, adaptive, random (two choices), consistent hash of path / URI / host / header / cookie / query parameter / client IP with optional bounded load, and IP hash; member weights, backup and draining members, sticky cookie or IP affinity; per-location backend groups with their own algorithm (HAProxy `use_backend` style); in-panel distribution simulator. Conditional routing: locations and whole-host rules selected by header, cookie, query parameter, method, client IP/CIDR, host or country (AND of conditions, negation, regex), with an in-panel routing tester. See [Load balancing](LOAD_BALANCING.md) | | Health checks | Active TCP or HTTP probes with thresholds, optional separate probe port, expected response text and live health status per member | | Connection reuse | Bounded keep-alive pools with idle and age limits, pool recycling and protocol telemetry | | Custom locations | Prefix, exact and regex paths, path rewriting, per-location backends, Web Services, local responses, redirects and internal error fallbacks | diff --git a/docs/HEADLESS.md b/docs/HEADLESS.md index ea9067d..c51446d 100644 --- a/docs/HEADLESS.md +++ b/docs/HEADLESS.md @@ -79,7 +79,7 @@ The smallest useful file is a single vhost ([`examples/headless-minimal.json`](. ``` - Up to 32 backends per vhost. `allow_private` is required for loopback and private addresses. -- `algorithm`: `round_robin`, `least_connections` (default), `least_traffic`, `adaptive` or `ip_hash`; `sticky` sessions are configured as in [Vhosts](VHOSTS.md). +- `algorithm`: `round_robin`, `least_connections` (default), `least_traffic`, `adaptive`, `random`, `hash` (with a `hash` object: `source`, `name`, `path_depth`, `ignore_case`, `balance_factor`, `fallback`) or `ip_hash`; `sticky` sessions are configured as in [Vhosts](VHOSTS.md). Routes can set `backend_ids` and their own `load_balancing`; see [Load balancing](LOAD_BALANCING.md). - By default requests with cookies or `Authorization` and responses with `Set-Cookie` are not cached, so enabling the cache for an application with logins only stores public responses and static files. - With an HTTPS listener and the `*` host, clients that use an IP address or an unknown name receive the default certificate (self-signed unless `tls.default_certificate` points to your own). @@ -383,7 +383,7 @@ curl -s http://127.0.0.1:9091/certificates | jq '.certificates[] | {id, source, | Health checks / outlier detection | `health_check` (active), `passive_health` (ejection after real failures), `slow_start_seconds` | | Retry policy | `retry` (`max_retries`, connect errors, timeouts, statuses) | | Circuit breakers (`max_requests`, `max_pending_requests`) | backend `max_concurrent_requests` + `queue_timeout_ms`, vhost `rate_limit` | -| Sticky sessions / hash policy | `sticky`, `ip_hash` | +| Sticky sessions / hash policy | `sticky`, `ip_hash`, `hash` (consistent: path, header, cookie, query, IP; `balance_factor` for bounded load) | | Admin `/ready`, `/clusters`, `/certs` | `/healthz` (pools), `/certificates` on `--health-listen`; Prometheus `/metrics` | | Hot restart | `SIGHUP` reload without dropping connections; listener changes need a restart | diff --git a/docs/LOAD_BALANCING.md b/docs/LOAD_BALANCING.md new file mode 100644 index 0000000..e940402 --- /dev/null +++ b/docs/LOAD_BALANCING.md @@ -0,0 +1,136 @@ +# Load balancing algorithms and location backend groups + +Every reverse-proxy Vhost has one backend pool. Since 0.40.2 the pool can also balance by a **consistent hash of a request key** (path, URI, host, header, cookie, query parameter or client IP), and each **custom location** can send its requests to its own **backend group** with its **own algorithm** — the RustProxy equivalent of a HAProxy `use_backend` rule pointing at a backend with a different `balance` line. + +Configure it in the panel under **Vhosts → Edit → Backends → Balancing** (whole Vhost) and **Vhosts → Edit → Custom locations → Backends & balancing** (one location). + +## Algorithms + +| `algorithm` | Behaviour | HAProxy equivalent | +|---|---|---| +| `least_connections` (default) | Fewest in-flight requests per weight. | `balance leastconn` | +| `round_robin` | Smooth weighted round robin. | `balance roundrobin` | +| `least_traffic` | Fewest bytes per second (EWMA) per weight. | — | +| `adaptive` | In-flight requests × measured latency + traffic, per weight. | — | +| `random` | Two random members, the less loaded one wins (power of two choices). | `balance random(2)` | +| `hash` | Consistent hash of the key configured in `hash`. | `balance hash …` / `uri` / `hdr()` / `url_param` + `hash-type consistent` | +| `ip_hash` | Consistent hash of the client address (kept for compatibility; equivalent to `hash` with `source: "ip"`). | `balance source` + `hash-type consistent` | + +Weights, `backup`, `drain`, health checks, passive ejection, slow start and concurrency limits apply to every algorithm. + +## Consistent hashing (`hash`) + +RustProxy ranks the members for each key with **weighted rendezvous hashing** (highest random weight). Hashing is always consistent — there is no map-based mode: + +- the same key always selects the same member while that member is eligible; +- when a member fails, is drained, disabled or removed, **only the keys of that member move**, and they return when it recovers; +- a member with weight 3 receives about three times as many keys as a member with weight 1; +- when the preferred member is at its `max_concurrent_requests` limit the next member in the key's order is used for that request. + +`load_balancing.hash` settings (all optional): + +| Field | Default | Meaning | +|---|---|---| +| `source` | `path` | `path` (path without query, as received from the client, before location rewrites), `uri` (path + query string), `host` (host name without port), `header`, `cookie`, `query` (one query parameter) or `ip` (client address seen by RustProxy). | +| `name` | — | Header, cookie or query parameter name; required for `header`, `cookie` and `query`, rejected otherwise. Header values from repeated lines are joined with `,`; the first matching cookie/parameter is used; values are not URL-decoded. | +| `path_depth` | `0` | For `path`/`uri`: hash only the first N directories (`/music/album/01.mp3` with depth 2 hashes `/music/album`), so a whole directory stays on one member. `0` hashes the whole path. Range 0–32. | +| `ignore_case` | `false` | Lower-case the key before hashing (useful for file names that differ only in case). | +| `balance_factor` | `0` | Consistent hashing with bounded loads, like HAProxy `hash-balance-factor`: a member may take a new request only while its in-flight requests stay within this percentage of its weighted share of the pool load; otherwise the next member for that key is used. `0` disables the bound; otherwise 101–1000 (125 is a common choice). Hot keys spill over deterministically and return when the load drops. | +| `fallback` | `round_robin` | Algorithm for requests without a key value (missing header, cookie or parameter): `round_robin`, `least_connections`, `least_traffic`, `adaptive` or `random`. | + +Sticky affinity, when enabled, takes precedence over the algorithm: an `ip_hash` sticky mode always hashes the client address, and a valid affinity cookie selects its member before hashing. + +The client IP is the transport peer (or the address accepted from trusted forwarding settings); `X-Forwarded-For` sent by a client cannot change it. + +### Example: the whole Vhost hashes by path + +```json +"load_balancing": { + "algorithm": "hash", + "hash": { "source": "path", "ignore_case": true, "balance_factor": 150 }, + "health_check": { "mode": "http", "path": "/health" } +} +``` + +### Example: per-tenant routing by header, round robin without the header + +```json +"load_balancing": { + "algorithm": "hash", + "hash": { "source": "header", "name": "X-Tenant", "fallback": "least_connections" } +} +``` + +## Location backend groups + +A custom location with the **Proxy** action chooses its backends with `backend_ids` and, optionally, its own balancing with `load_balancing`: + +| Location field | Meaning | +|---|---| +| `backend_id` | Pin one backend (unchanged). Cannot be combined with the two fields below. | +| `backend_ids` | Backend group: ids of Vhost backends (up to 64, no duplicates). Empty means the whole Vhost pool. Members whose `pool_eligible` is `false` (“Include in the default load-balancing pool” off) are used **only** by locations that list them. | +| `load_balancing` | Location balancing: `algorithm`, `hash` (same fields as above) and `sticky` (`off` default, `cookie` or `ip_hash`). Without it the location inherits the Vhost algorithm, hash settings and affinity. | + +Members are shared with the Vhost pool: active and passive health, ejection, draining, concurrency limits, retries, slow start and statistics are the same objects, and the **Backends** status view shows them once. Retries stay within the location's group. A location affinity cookie is named `__` so it never competes with the Vhost cookie, and affinity cookies of the Vhost and its locations are stripped before requests reach an origin. + +### Example: HAProxy `use_backend mp3_shards if is_mp3` with `balance hash path` + +HAProxy: + +``` +frontend https_front + acl is_mp3 path_end -i .mp3 + use_backend mp3_shards if is_mp3 + +backend mp3_shards + balance hash path + hash-type consistent + server mp3_1 10.0.0.11:80 check + server mp3_2 10.0.0.12:80 check + server mp3_3 10.0.0.13:80 check +``` + +RustProxy Vhost: + +```json +{ + "id": "music", + "frontend": { "hosts": ["music.example.com"], "listener_ids": ["https"] }, + "backends": [ + { "id": "app", "url": "http://10.0.0.5:8080", "allow_private": true }, + { "id": "mp3_1", "url": "http://10.0.0.11:80", "allow_private": true, "pool_eligible": false }, + { "id": "mp3_2", "url": "http://10.0.0.12:80", "allow_private": true, "pool_eligible": false }, + { "id": "mp3_3", "url": "http://10.0.0.13:80", "allow_private": true, "pool_eligible": false } + ], + "load_balancing": { "algorithm": "least_connections", "health_check": { "mode": "tcp" } }, + "routes": [ + { + "id": "mp3", + "match_type": "regex_insensitive", + "path_prefix": "\\.mp3$", + "backend_ids": ["mp3_1", "mp3_2", "mp3_3"], + "load_balancing": { "algorithm": "hash", "hash": { "source": "path" } } + } + ] +} +``` + +`path_end -i .mp3` becomes a case-insensitive regex location; `check` corresponds to the Vhost health check (TCP by default). Everything else on the host keeps using `app` with least connections. + +In the panel: add the three backends with **Include in the default load-balancing pool** off, add a custom location, choose **Backends → Backend group**, tick the three backends, turn on **Own balancing for this location** and click **Files / cache shards by path**. + +Locations can additionally require request conditions (header, cookie, query parameter, method, client IP, host, country), and a match type `any` turns a location into a rule for the whole host — together the full HAProxy `use_backend if ` pattern. See [Custom locations → Request conditions](CUSTOM_LOCATIONS.md#request-conditions-routing-by-header-cookie-ip). + +## Panel helpers + +- **Quick setup** buttons fill typical combinations: files by path, session cookie, tenant header, query parameter, client IP, or even load spreading. +- Each algorithm shows a short explanation, and hash settings show the **HAProxy equivalent** lines for comparison. +- **Test distribution** runs in the browser on the unsaved draft. Paste sample paths, URLs or key values to see the hash key and the selected backend for each, the share per backend, and — after ticking **Simulate failure of** — which keys would move. The simulator uses the same SHA-256 rendezvous scoring as the proxy (checked by `tools/dev/test_balance_simulator.js`); load-based algorithms show the expected share by weight instead. It does not account for current concurrency limits, bounded-load spill-over or live health. + +## Compatibility and limits + +- Configurations without `hash`, `backend_ids` or location `load_balancing` load and behave exactly as before; these fields are omitted when unset, so saved files stay unchanged. `ip_hash` keeps the same client → backend mapping as earlier versions. +- A configuration that uses the new fields is rejected by 0.40.1 and older. +- Hashing reads the request as received. Changing a member id changes its keys; renaming the Vhost id reshuffles all keys (the Vhost id is part of the hash input). +- Consistent hashing spreads **keys**, not requests: a few very popular keys still load their members more. Use `balance_factor` for hot keys, or weights. +- Headless JSON uses the same fields; the panel and API validate them before activation. diff --git a/docs/README.md b/docs/README.md index 2f236c1..3556c23 100644 --- a/docs/README.md +++ b/docs/README.md @@ -22,7 +22,8 @@ Guides for operating RustProxy: installation, publishing services, security, cer ## Publishing services - [Vhosts and backends](VHOSTS.md) — domains, listeners, backends, balancing, health checks and redirects. -- [Custom locations](CUSTOM_LOCATIONS.md) — path routing, rewrites, local responses and error fallbacks. +- [Custom locations](CUSTOM_LOCATIONS.md) — path routing, request conditions (header, cookie, IP, method, country), whole-host rules, rewrites, local responses and error fallbacks. +- [Load balancing](LOAD_BALANCING.md) — algorithms, consistent hashing by path/header/cookie/query/IP, location backend groups and the distribution simulator. - [Web Server](WEB_SERVER.md) — static sites, downloads, `try_files`, rewrites, `.htaccess` subset and error pages. - [PHP-FPM](PHP_FPM.md) — PHP profiles, pool isolation and application examples. - [HTTP transport and TLS](TRANSPORT.md) — HTTPS, HTTP/2, HTTP/3, WebSockets, backend protocols and post-quantum key exchange. diff --git a/docs/VHOSTS.md b/docs/VHOSTS.md index af8c1f5..b812a6e 100644 --- a/docs/VHOSTS.md +++ b/docs/VHOSTS.md @@ -53,7 +53,7 @@ Under **Vhosts → Edit → Security → Country access**, choose `Off`, `Block` - **Reverse Proxy:** one Vhost has a backend pool. Each member has a configured URL, ID, enabled flag, weight, optional backup/drain state, health settings and capacity limits. - **Web Server:** Vhost references a Web Service by ID. Its document root, directory handling, PHP options and static-file headers remain configured under **Web Server**. -- **Custom locations:** can override selected URL paths and use the default pool, a pinned backend, a different Web Service, a redirect or a local response. Unmatched paths still use the main source. +- **Custom locations:** can override selected URL paths and use the default pool, a backend group with its own balancing, a pinned backend, a different Web Service, a redirect or a local response. Unmatched paths still use the main source. Locations and whole-host rules can also require conditions on headers, cookies, query parameters, method, client IP, host or country — see [Request conditions](CUSTOM_LOCATIONS.md#request-conditions-routing-by-header-cookie-ip). Sample documents in `examples/vhosts-private.json` and `examples/vhosts-balanced.json` illustrate JSON formats, but their IP addresses, certificates and health endpoints are examples only. @@ -72,7 +72,7 @@ Connection reuse is bounded by configured idle-pool/recycle limits. The default ## Load balancing and health -Backend pools support scheduling/weighting, standby members, draining and optional session affinity. Check the **Backends** status view for member health, recently observed HTTP response code, upstream protocol and resource usage. A reported status from normal traffic is not necessarily the result of a health probe. +Backend pools support scheduling/weighting, standby members, draining and optional session affinity. Algorithms are least connections (default), round robin, least traffic, adaptive, random (two choices), consistent hash of a request key (path, URI, host, header, cookie, query parameter or client IP, with optional bounded load) and IP hash; a custom location can use its own backend group and algorithm. See [Load balancing](LOAD_BALANCING.md), including a HAProxy `use_backend` + `balance hash path` example and the panel's distribution simulator. Check the **Backends** status view for member health, recently observed HTTP response code, upstream protocol and resource usage. A reported status from normal traffic is not necessarily the result of a health probe. - Health monitoring may use TCP or HTTP checks with a path, Host, interval and thresholds. Avoid write endpoints; use a lightweight `/health` or equivalent. - **Health check port** (`health_check.port`) probes a different port than the one receiving traffic, like `check port` in HAProxy. Example: a backend serving traffic on `http://10.0.0.5:80` with a status endpoint on port `8079` uses `"health_check": {"mode": "http", "path": "/status", "port": 8079}`. The probe keeps the backend host, scheme, TLS settings and address restrictions; only the port changes. Leave it empty to probe the traffic port. The port can be set for the whole pool or per backend. diff --git a/langs/en_US.json b/langs/en_US.json index bfa18aa..ebd8abe 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -3909,6 +3909,111 @@ "cacheReason_response_static_not_public": "Static asset with Cookie: backend did not declare public freshness", "cacheReason_response_static_dynamic": "Static asset with Cookie: HTML/dynamic content type", "cacheReason_response_vary_cookie": "Vary: Cookie kept (not explicitly public)", - "cacheReason_response_surrogate_control": "Surrogate-Control no-store" + "cacheReason_response_surrogate_control": "Surrogate-Control no-store", + "lbRandom": "Random (power of two choices)", + "lbHash": "Consistent hash of a request key", + "lbSourcePath": "Path (without query)", + "lbSourceUri": "Path + query string", + "lbSourceHost": "Host name", + "lbSourceHeader": "Request header", + "lbSourceCookie": "Cookie", + "lbSourceQuery": "Query parameter", + "lbSourceIp": "Client IP", + "lbPresets": "Quick setup", + "lbPresetFiles": "Files / cache shards by path", + "lbPresetCookie": "Session cookie", + "lbPresetTenant": "Tenant header", + "lbPresetQuery": "Query parameter", + "lbPresetIp": "Client IP", + "lbPresetEven": "Spread load evenly", + "lbLocationSticky": "Affinity for this location", + "lbHashSource": "Hash key", + "lbHashName": "Header / cookie / parameter name", + "lbHashDepth": "Path depth (0 = whole path)", + "lbHashFactor": "Bounded load % (0 = off, 101–1000)", + "lbHashFallback": "When the key is missing", + "lbHashIgnoreCase": "Ignore letter case", + "lbHashNameRequired": "Enter the header, cookie or query parameter name used as the hash key.", + "lbHaproxyEquivalent": "HAProxy equivalent", + "lbSimulator": "Test distribution", + "lbSimulateDown": "Simulate failure of", + "lbSimNoMembers": "No backend can receive traffic (all disabled, draining or failed).", + "lbSimLoadBased": "This algorithm decides per request from current load, so individual requests cannot be predicted. Expected long-run share by weight:", + "lbSimRequest": "Sample", + "lbSimKey": "Hash key", + "lbSimNoKey": "no key", + "lbSimFallback": "fallback", + "lbSimMoved": "{moved} of {total} keys moved to another backend; all other keys stayed where they were (consistent hashing).", + "lbSimStable": "The same key always goes to the same backend. Tick a backend above to see which keys would move if it failed.", + "lbSimSamples": "Sample requests (one per line: /path?query or https://host/path)", + "lbSimSamples_header": "Sample header values (one per line)", + "lbSimSamples_cookie": "Sample cookie values (one per line)", + "lbSimSamples_ip": "Sample client addresses (one per line)", + "lbDescribe_round_robin": "Takes turns in proportion to weights. Good default for identical, stateless backends.", + "lbDescribe_least_connections": "Sends each request to the backend with the fewest in-flight requests per weight. Best for mixed request durations.", + "lbDescribe_least_traffic": "Prefers the backend moving the fewest bytes per second (EWMA). Useful for downloads and streaming.", + "lbDescribe_adaptive": "Combines in-flight requests, measured latency and traffic. Adapts to slower or overloaded backends.", + "lbDescribe_random": "Picks two random backends and uses the less loaded one. Scales well with many proxies and backends.", + "lbDescribe_hash": "The same key always lands on the same backend (weighted rendezvous hashing, always consistent). When a backend fails or is removed, only its own keys move. Ideal for cache shards, file storage and per-user state. Cookie or IP affinity, if enabled, takes precedence.", + "lbDescribe_ip_hash": "Consistent hash of the client address. Prefer “Consistent hash” with the Client IP key for new setups.", + "lbKeyHelp_path": "Hashes the request path as received from the client, before location rewrites. Like HAProxy “balance hash path” / “balance uri”. Use path depth to keep a whole directory (e.g. an album) on one backend.", + "lbKeyHelp_uri": "Hashes the path and the query string, so /file?v=1 and /file?v=2 can land on different backends.", + "lbKeyHelp_host": "Hashes the requested host name without the port. Useful for wildcard vhosts that serve many sites.", + "lbKeyHelp_header": "Hashes the value of one request header, e.g. X-Tenant or X-User-Id. Requests without it use the fallback algorithm.", + "lbKeyHelp_cookie": "Hashes the value of one cookie set by your application, e.g. its session id. Requests without it use the fallback algorithm.", + "lbKeyHelp_query": "Hashes one query parameter, e.g. ?id=…. Requests without it use the fallback algorithm.", + "lbKeyHelp_ip": "Hashes the client address seen by RustProxy (forwarded headers cannot spoof it).", + "locationTarget": "Backends", + "locationBackendGroup": "Backend group (choose below)", + "locationBalancing": "Backends & balancing", + "locationGroupMembers": "Backends in this group", + "locationGroupHelp": "Like a HAProxy “use_backend”: requests matching this location go only to the ticked backends. Backends with “Include in the default load-balancing pool” turned off serve only locations that select them. Health checks and limits are shared with the vhost.", + "locationOnlyTag": "location only", + "lbLocationOwn": "Own balancing for this location", + "lbLocationInherit": "This location uses the vhost algorithm and affinity. Turn on own balancing to hash by path, header, cookie and more.", + "locationGroupEmpty": "Location {location}: tick at least one backend for its backend group.", + "locationMatchAny": "Any path (rule for the whole host)", + "locationMatch_any": "any path", + "rtAddHostRule": "Add rule for the whole host", + "rtOrderHelp": "Order: exact paths, then priority prefixes, then regular expressions and whole-host rules from top to bottom, then the longest prefix. Locations with conditions are used only when all their conditions hold; otherwise the next candidate is tried. Use ↑ / ↓ to change the order.", + "rtConditions": "Conditions (header, cookie, IP…)", + "rtConditionsHelp": "All conditions must hold (AND). One condition matches when any of its values matches (OR, one value per line). For an OR between rules, add several locations. Like HAProxy ACLs in “use_backend … if …”.", + "rtNotCachedHelp": "Responses of a location with conditions are never cached, because they depend on request attributes that are not part of the cache key.", + "rtMoveUp": "↑ Up", + "rtMoveDown": "↓ Down", + "rtConditionCount": "{count} condition(s)", + "rtSourceHeader": "Header", + "rtSourceCookie": "Cookie", + "rtSourceQuery": "Query parameter", + "rtSourceMethod": "Method", + "rtSourceIp": "Client IP", + "rtSourceHost": "Host", + "rtSourceCountry": "Country", + "rtOpEquals": "equals", + "rtOpExists": "exists", + "rtOpPrefix": "starts with", + "rtOpSuffix": "ends with", + "rtOpContains": "contains", + "rtOpRegex": "matches regex", + "rtOpCidr": "in network (IP/CIDR)", + "rtNoConditions": "No conditions: the location is selected by its path alone.", + "rtTooMany": "At most 16 conditions per location.", + "rtSource": "Condition source", + "rtOperator": "Operator", + "rtName": "Name", + "rtValues": "Values (one per line)", + "rtValuesPlaceholder": "value (one per line)", + "rtNegate": "NOT (negate)", + "rtAddCondition": "Add condition", + "rtTester": "Test routing", + "rtUrl": "URL or path", + "rtHeaders": "Request headers (Name: value)", + "rtMainSource": "main source of the vhost", + "rtResult": "Handled by:", + "rtNotCached": "not cached", + "rtPathColumn": "Path", + "rtConditionsColumn": "Conditions", + "rtBrowserRegex": "the browser cannot evaluate this expression", + "rtTesterHelp": "The test runs in the browser on the unsaved draft. Regular expressions are evaluated with the browser engine, which supports the same common syntax as RustProxy; the saved configuration is always validated by the server." } } diff --git a/langs/pl_pl.json b/langs/pl_pl.json index b1d4924..49260fe 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -3909,6 +3909,111 @@ "cacheReason_response_static_not_public": "Statyk z Cookie: backend nie zadeklarował publicznej świeżości", "cacheReason_response_static_dynamic": "Statyk z Cookie: treść HTML/dynamiczna", "cacheReason_response_vary_cookie": "Zachowano Vary: Cookie (brak jawnego public)", - "cacheReason_response_surrogate_control": "Surrogate-Control no-store" + "cacheReason_response_surrogate_control": "Surrogate-Control no-store", + "lbRandom": "Losowy (dwa losowe wybory)", + "lbHash": "Spójny skrót klucza żądania", + "lbSourcePath": "Ścieżka (bez zapytania)", + "lbSourceUri": "Ścieżka + query string", + "lbSourceHost": "Nazwa hosta", + "lbSourceHeader": "Nagłówek żądania", + "lbSourceCookie": "Ciasteczko", + "lbSourceQuery": "Parametr zapytania", + "lbSourceIp": "IP klienta", + "lbPresets": "Szybka konfiguracja", + "lbPresetFiles": "Pliki / shardy cache wg ścieżki", + "lbPresetCookie": "Ciasteczko sesji", + "lbPresetTenant": "Nagłówek klienta (tenant)", + "lbPresetQuery": "Parametr zapytania", + "lbPresetIp": "IP klienta", + "lbPresetEven": "Równomierne obciążenie", + "lbLocationSticky": "Przyklejanie dla tej lokalizacji", + "lbHashSource": "Klucz skrótu", + "lbHashName": "Nazwa nagłówka / ciasteczka / parametru", + "lbHashDepth": "Głębokość ścieżki (0 = cała ścieżka)", + "lbHashFactor": "Ograniczenie obciążenia % (0 = wył., 101–1000)", + "lbHashFallback": "Gdy brak klucza", + "lbHashIgnoreCase": "Ignoruj wielkość liter", + "lbHashNameRequired": "Podaj nazwę nagłówka, ciasteczka lub parametru używanego jako klucz skrótu.", + "lbHaproxyEquivalent": "Odpowiednik w HAProxy", + "lbSimulator": "Przetestuj rozkład", + "lbSimulateDown": "Symuluj awarię", + "lbSimNoMembers": "Żaden backend nie może przyjąć ruchu (wszystkie wyłączone, wygaszane lub niedostępne).", + "lbSimLoadBased": "Ten algorytm decyduje przy każdym żądaniu na podstawie bieżącego obciążenia, więc nie da się przewidzieć pojedynczych żądań. Oczekiwany udział wg wag:", + "lbSimRequest": "Próbka", + "lbSimKey": "Klucz skrótu", + "lbSimNoKey": "brak klucza", + "lbSimFallback": "zastępczo", + "lbSimMoved": "{moved} z {total} kluczy trafiło do innego backendu; pozostałe zostały na miejscu (spójne haszowanie).", + "lbSimStable": "Ten sam klucz zawsze trafia do tego samego backendu. Zaznacz backend powyżej, aby zobaczyć, które klucze przeniosą się przy jego awarii.", + "lbSimSamples": "Przykładowe żądania (jedno w wierszu: /ścieżka?query lub https://host/ścieżka)", + "lbSimSamples_header": "Przykładowe wartości nagłówka (jedna w wierszu)", + "lbSimSamples_cookie": "Przykładowe wartości ciasteczka (jedna w wierszu)", + "lbSimSamples_ip": "Przykładowe adresy klientów (jeden w wierszu)", + "lbDescribe_round_robin": "Po kolei, proporcjonalnie do wag. Dobry wybór dla identycznych, bezstanowych backendów.", + "lbDescribe_least_connections": "Każde żądanie trafia do backendu z najmniejszą liczbą trwających żądań na wagę. Najlepszy przy zróżnicowanym czasie obsługi.", + "lbDescribe_least_traffic": "Wybiera backend przesyłający najmniej bajtów na sekundę (EWMA). Przydatny przy pobieraniu plików i streamingu.", + "lbDescribe_adaptive": "Łączy trwające żądania, zmierzone opóźnienie i ruch. Omija wolniejsze lub przeciążone backendy.", + "lbDescribe_random": "Losuje dwa backendy i wybiera mniej obciążony. Dobrze się skaluje przy wielu proxy i backendach.", + "lbDescribe_hash": "Ten sam klucz zawsze trafia do tego samego backendu (ważone haszowanie rendezvous, zawsze spójne). Gdy backend padnie lub zostanie usunięty, przenoszą się tylko jego klucze. Idealne dla shardów cache, magazynów plików i stanu per użytkownik. Włączone przyklejanie (ciasteczko lub IP) ma pierwszeństwo.", + "lbDescribe_ip_hash": "Spójny skrót adresu klienta. W nowych konfiguracjach wybierz „Spójny skrót” z kluczem „IP klienta”.", + "lbKeyHelp_path": "Haszuje ścieżkę żądania w postaci od klienta, przed przepisaniem przez lokalizację. Jak „balance hash path” / „balance uri” w HAProxy. Głębokość ścieżki pozwala trzymać cały katalog (np. album) na jednym backendzie.", + "lbKeyHelp_uri": "Haszuje ścieżkę razem z query stringiem, więc /plik?v=1 i /plik?v=2 mogą trafić do różnych backendów.", + "lbKeyHelp_host": "Haszuje żądaną nazwę hosta bez portu. Przydatne dla vhostów wildcard obsługujących wiele serwisów.", + "lbKeyHelp_header": "Haszuje wartość jednego nagłówka, np. X-Tenant lub X-User-Id. Żądania bez niego obsłuży algorytm zastępczy.", + "lbKeyHelp_cookie": "Haszuje wartość ciasteczka ustawianego przez aplikację, np. identyfikator sesji. Żądania bez niego obsłuży algorytm zastępczy.", + "lbKeyHelp_query": "Haszuje jeden parametr zapytania, np. ?id=…. Żądania bez niego obsłuży algorytm zastępczy.", + "lbKeyHelp_ip": "Haszuje adres klienta widziany przez RustProxy (nagłówki przekazywania go nie podmienią).", + "locationTarget": "Backendy", + "locationBackendGroup": "Grupa backendów (wybierz poniżej)", + "locationBalancing": "Backendy i balansowanie", + "locationGroupMembers": "Backendy w tej grupie", + "locationGroupHelp": "Jak „use_backend” w HAProxy: żądania pasujące do tej lokalizacji trafiają tylko do zaznaczonych backendów. Backendy z wyłączonym „Uwzględnij w domyślnej puli backendów” obsługują tylko lokalizacje, które je wybiorą. Kontrole zdrowia i limity są wspólne z vhostem.", + "locationOnlyTag": "tylko lokalizacje", + "lbLocationOwn": "Własne balansowanie dla tej lokalizacji", + "lbLocationInherit": "Ta lokalizacja używa algorytmu i przyklejania vhosta. Włącz własne balansowanie, aby haszować po ścieżce, nagłówku, ciasteczku i innych.", + "locationGroupEmpty": "Lokalizacja {location}: zaznacz co najmniej jeden backend w jej grupie backendów.", + "locationMatchAny": "Dowolna ścieżka (reguła dla całego hosta)", + "locationMatch_any": "dowolna ścieżka", + "rtAddHostRule": "Dodaj regułę dla całego hosta", + "rtOrderHelp": "Kolejność: dokładne ścieżki, potem prefiksy priorytetowe, potem wyrażenia regularne i reguły dla całego hosta od góry do dołu, a na końcu najdłuższy prefiks. Lokalizacja z warunkami jest użyta tylko, gdy wszystkie jej warunki są spełnione; w przeciwnym razie sprawdzany jest kolejny kandydat. Kolejność zmienisz przyciskami ↑ / ↓.", + "rtConditions": "Warunki (nagłówek, ciasteczko, IP…)", + "rtConditionsHelp": "Wszystkie warunki muszą być spełnione (AND). Pojedynczy warunek pasuje, gdy pasuje dowolna z jego wartości (OR, jedna wartość w wierszu). Dla OR między regułami dodaj kilka lokalizacji. Jak ACL-e w HAProxy w „use_backend … if …”.", + "rtNotCachedHelp": "Odpowiedzi lokalizacji z warunkami nigdy nie trafiają do cache, bo zależą od cech żądania spoza klucza cache.", + "rtMoveUp": "↑ W górę", + "rtMoveDown": "↓ W dół", + "rtConditionCount": "warunki: {count}", + "rtSourceHeader": "Nagłówek", + "rtSourceCookie": "Ciasteczko", + "rtSourceQuery": "Parametr zapytania", + "rtSourceMethod": "Metoda", + "rtSourceIp": "IP klienta", + "rtSourceHost": "Host", + "rtSourceCountry": "Kraj", + "rtOpEquals": "równa się", + "rtOpExists": "istnieje", + "rtOpPrefix": "zaczyna się od", + "rtOpSuffix": "kończy się na", + "rtOpContains": "zawiera", + "rtOpRegex": "pasuje do regexu", + "rtOpCidr": "w sieci (IP/CIDR)", + "rtNoConditions": "Brak warunków: lokalizację wybiera sama ścieżka.", + "rtTooMany": "Maksymalnie 16 warunków na lokalizację.", + "rtSource": "Źródło warunku", + "rtOperator": "Operator", + "rtName": "Nazwa", + "rtValues": "Wartości (jedna w wierszu)", + "rtValuesPlaceholder": "wartość (jedna w wierszu)", + "rtNegate": "NIE (zaprzeczenie)", + "rtAddCondition": "Dodaj warunek", + "rtTester": "Testuj trasowanie", + "rtUrl": "URL lub ścieżka", + "rtHeaders": "Nagłówki żądania (Nazwa: wartość)", + "rtMainSource": "główne źródło vhosta", + "rtResult": "Obsłuży:", + "rtNotCached": "bez cache", + "rtPathColumn": "Ścieżka", + "rtConditionsColumn": "Warunki", + "rtBrowserRegex": "przeglądarka nie potrafi obliczyć tego wyrażenia", + "rtTesterHelp": "Test działa w przeglądarce na niezapisanym szkicu. Wyrażenia regularne liczy silnik przeglądarki, który obsługuje tę samą typową składnię co RustProxy; zapisaną konfigurację zawsze sprawdza serwer." } } diff --git a/src/admin/documentation/documents.rs b/src/admin/documentation/documents.rs index 46bbecd..871fddf 100644 --- a/src/admin/documentation/documents.rs +++ b/src/admin/documentation/documents.rs @@ -20,6 +20,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[ reader_doc!("docs/HEADLESS.md", "guides"), reader_doc!("docs/VHOSTS.md", "guides"), reader_doc!("docs/CUSTOM_LOCATIONS.md", "guides"), + reader_doc!("docs/LOAD_BALANCING.md", "guides"), reader_doc!("docs/ACCESS.md", "guides"), reader_doc!("docs/WEB_SERVER.md", "guides"), reader_doc!("docs/PHP_FPM.md", "guides"), diff --git a/src/admin/openapi.json b/src/admin/openapi.json index ddf64d7..a596f0b 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -290,7 +290,34 @@ }, "backend_id": { "type": "string", - "nullable": true + "nullable": true, + "description": "Pin one Vhost backend. Cannot be combined with backend_ids or load_balancing." + }, + "backend_ids": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { + "type": "string" + }, + "description": "Backend group of this location (Vhost backend ids). Empty: the Vhost pool. Members with pool_eligible=false serve only locations that list them." + }, + "load_balancing": { + "allOf": [ + { + "$ref": "#/components/schemas/LocationBalancing" + } + ], + "nullable": true, + "description": "Own algorithm/hash/affinity for this location; null inherits the Vhost settings." + }, + "conditions": { + "type": "array", + "maxItems": 16, + "items": { + "$ref": "#/components/schemas/RouteCondition" + }, + "description": "Extra request conditions; all must hold (AND). A location whose conditions fail is skipped and the next candidate is tried. Responses of conditional locations are never cached (cache must be null or false)." }, "enabled": { "type": "boolean" @@ -328,10 +355,11 @@ "prefix_priority", "exact", "regex", - "regex_insensitive" + "regex_insensitive", + "any" ], "default": "prefix", - "description": "Nginx-style location matching: prefix, priority prefix (^~), exact (=), regex (~), or case-insensitive regex (~*)." + "description": "`any` matches every path: a whole-host rule selected only by its `conditions` (required), evaluated with regular expressions in list order." }, "rewrite": { "type": "object", @@ -5204,9 +5232,12 @@ "least_connections", "least_traffic", "adaptive", + "random", + "hash", "ip_hash" ], - "default": "least_connections" + "default": "least_connections", + "description": "`hash` uses the consistent (weighted rendezvous) hash configured in `hash`; `random` picks the less loaded of two random members; `ip_hash` equals `hash` with source `ip`." }, "health_check": { "$ref": "#/components/schemas/DockerHealthCheck", @@ -5330,6 +5361,9 @@ "minimum": 0, "maximum": 300, "default": 10 + }, + "hash": { + "$ref": "#/components/schemas/HashSettings" } } }, @@ -9006,6 +9040,151 @@ "description": "Resolved effective cache settings; only in full Cache responses." } } + }, + "HashSettings": { + "type": "object", + "additionalProperties": false, + "description": "Key of the `hash` algorithm. Hashing is always consistent: removing or ejecting a member only moves its own keys. Omitted when all fields have their defaults.", + "properties": { + "source": { + "type": "string", + "enum": [ + "path", + "uri", + "host", + "ip", + "header", + "cookie", + "query" + ], + "default": "path", + "description": "path: request path without query as received from the client; uri: path and query; host: host name without port; ip: client address; header/cookie/query: value named by `name`." + }, + "name": { + "type": "string", + "maxLength": 128, + "description": "Header, cookie or query parameter name; required for header/cookie/query and rejected for other sources." + }, + "path_depth": { + "type": "integer", + "minimum": 0, + "maximum": 32, + "default": 0, + "description": "For path/uri: number of leading directories hashed; 0 hashes the whole path." + }, + "ignore_case": { + "type": "boolean", + "default": false + }, + "balance_factor": { + "type": "integer", + "minimum": 0, + "maximum": 1000, + "default": 0, + "description": "Bounded load in percent of the weighted average (HAProxy hash-balance-factor). 0 disables; otherwise 101..1000." + }, + "fallback": { + "type": "string", + "enum": [ + "round_robin", + "least_connections", + "least_traffic", + "adaptive", + "random" + ], + "default": "round_robin", + "description": "Algorithm for requests without a key value." + } + } + }, + "LocationBalancing": { + "type": "object", + "additionalProperties": false, + "description": "Location-specific balancing over the location's backend group (or the whole Vhost pool). Members, health and limits are shared with the Vhost pool.", + "properties": { + "algorithm": { + "type": "string", + "enum": [ + "round_robin", + "least_connections", + "least_traffic", + "adaptive", + "random", + "hash", + "ip_hash" + ], + "default": "hash" + }, + "hash": { + "$ref": "#/components/schemas/HashSettings" + }, + "sticky": { + "type": "string", + "enum": [ + "off", + "cookie", + "ip_hash" + ], + "default": "off", + "description": "Location affinity. The cookie is named `__`." + } + } + }, + "RouteCondition": { + "type": "object", + "additionalProperties": false, + "description": "One request condition of a location. Matches when any of `values` matches; `negate` inverts it.", + "properties": { + "source": { + "type": "string", + "enum": [ + "header", + "cookie", + "query", + "method", + "ip", + "host", + "country" + ], + "default": "header" + }, + "name": { + "type": "string", + "maxLength": 128, + "description": "Header, cookie or query parameter name (required for those sources, rejected otherwise)." + }, + "operator": { + "type": "string", + "enum": [ + "equals", + "exists", + "prefix", + "suffix", + "contains", + "regex", + "cidr" + ], + "default": "equals", + "description": "`cidr` only for `ip` (and the only operator for it); `method` and `country` use `equals`; `exists` takes no values and is not available for `host`." + }, + "values": { + "type": "array", + "maxItems": 64, + "items": { + "type": "string", + "maxLength": 1024 + } + }, + "negate": { + "type": "boolean", + "default": false + }, + "ignore_case": { + "type": "boolean", + "default": false, + "description": "Case-insensitive comparison for header, cookie and query values. Host, method and country always compare case-insensitively." + } + } } } }, diff --git a/src/admin/router.rs b/src/admin/router.rs index b946eca..67c310a 100644 --- a/src/admin/router.rs +++ b/src/admin/router.rs @@ -125,6 +125,8 @@ fn admin_vhosts_javascript() -> &'static str { include_str!("web/vhosts/protocol.js"), include_str!("web/vhosts/health.js"), include_str!("web/vhosts/rates.js"), + include_str!("web/vhosts/balancing.js"), + include_str!("web/vhosts/routing.js"), include_str!("web/vhosts/editor.js"), include_str!("web/vhosts/render.js"), "})();", diff --git a/src/admin/web/css/40-editors.css b/src/admin/web/css/40-editors.css index 9d3f9c5..46ef430 100644 --- a/src/admin/web/css/40-editors.css +++ b/src/admin/web/css/40-editors.css @@ -2183,4 +2183,250 @@ h2+.fine { transform: rotate(90deg); justify-self: start; } -} \ No newline at end of file +} +/* Load-balancing editor and distribution simulator (vhost and location). */ +.lb-editor { + display: grid; + gap: 10px; + min-width: 0; +} + +.lb-presets { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.lb-presets-label, +.lb-equivalent>span, +.lb-sim-down>span, +.location-group-title { + color: var(--muted); + font: 600 10px var(--mono); + letter-spacing: .35px; +} + +.lb-preset { + border-radius: 999px; + padding: 4px 10px; + font-size: 11px; +} + +.lb-description { + margin: 0; + color: var(--text); +} + +.lb-hash { + border-left: 2px solid var(--accent); + padding-left: 10px; +} + +.lb-equivalent pre { + margin: 4px 0 0; + padding: 7px 9px; + background: var(--code-bg); + border: 1px solid var(--line); + font: 11px var(--mono); + white-space: pre-wrap; +} + +.lb-simulator { + border: 1px solid var(--line); + background: var(--panel2); +} + +.lb-simulator>summary { + cursor: pointer; + padding: 9px 10px; + font-weight: 600; +} + +.lb-sim-body { + display: grid; + gap: 10px; + border-top: 1px solid var(--line); + padding: 10px; +} + +.lb-sim-inputs { + display: grid; + grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); + gap: 10px; +} + +.lb-sim-down-list, +.location-group-list { + display: flex; + flex-wrap: wrap; + gap: 4px 12px; + margin-top: 6px; +} + +.lb-bars { + display: grid; + gap: 4px; +} + +.lb-bar { + display: grid; + grid-template-columns: minmax(70px, 160px) minmax(0, 1fr) 90px; + align-items: center; + gap: 8px; + font-size: 11px; +} + +.lb-bar-label { + font-family: var(--mono); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.lb-bar-track { + height: 8px; + background: var(--field-bg); + border: 1px solid var(--line); +} + +.lb-bar-fill { + display: block; + height: 100%; + background: var(--green); +} + +.lb-bar-value { + color: var(--muted); + font-family: var(--mono); + text-align: right; +} + +.lb-sim-summary { + margin: 0; +} + +.lb-sim-table { + width: 100%; + border-collapse: collapse; + font-size: 11px; +} + +.lb-sim-table :is(th, td) { + border-bottom: 1px solid var(--row-line); + padding: 4px 6px; + text-align: left; + overflow-wrap: anywhere; +} + +.lb-sim-table tr.is-moved td { + background: var(--notice-bg); +} + +.lb-sim-table tr.is-fallback td { + color: var(--muted); +} + +.lb-moved { + color: var(--notice-text); + font-family: var(--mono); +} + +.location-group { + border: 1px solid var(--line); + padding: 8px 10px; +} + +/* Location conditions and routing tester. */ +.rt-conditions { + display: grid; + gap: 8px; +} + +.rt-condition-list { + display: grid; + gap: 6px; +} + +.rt-condition { + display: grid; + grid-template-columns: minmax(110px, 150px) minmax(90px, 160px) minmax(120px, 170px) minmax(140px, 1fr) auto auto auto; + align-items: center; + gap: 6px; +} + +.rt-condition :is(select, input[type=text], textarea) { + min-width: 0; + width: 100%; +} + +.rt-condition textarea { + min-height: 32px; + resize: vertical; + font-family: var(--mono); + font-size: 11px; +} + +.rt-flag { + white-space: nowrap; + font-size: 11px; +} + +.rt-empty { + margin: 0; +} + +.rt-tester { + border: 1px solid var(--accent); + background: var(--panel2); +} + +.rt-tester>summary { + cursor: pointer; + padding: 9px 10px; + font-weight: 600; +} + +.rt-tester-body { + display: grid; + gap: 10px; + border-top: 1px solid var(--line); + padding: 10px; +} + +.rt-verdict { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 6px; + font-size: 13px; +} + +.rt-target { + font-family: var(--mono); +} + +.rt-badge { + border: 1px solid var(--notice-line); + padding: 1px 6px; +} + +.rt-trace tr.is-winner td { + background: var(--nav-selected-bg); +} + +.rt-ok { + color: var(--green); + font-weight: 700; +} + +.rt-no, +.rt-error { + color: var(--red); + font-weight: 700; +} + +.rt-cond { + font-family: var(--mono); + font-size: 11px; +} diff --git a/src/admin/web/css/70-responsive.css b/src/admin/web/css/70-responsive.css index 0c8cfbd..0b5abf8 100644 --- a/src/admin/web/css/70-responsive.css +++ b/src/admin/web/css/70-responsive.css @@ -402,6 +402,18 @@ .traffic-donut { width: 120px; } + + .lb-sim-inputs { + grid-template-columns: 1fr; + } + + .rt-condition { + grid-template-columns: 1fr 1fr; + } + + .lb-bar { + grid-template-columns: minmax(60px, 110px) minmax(0, 1fr) 70px; + } } @media (max-width:700px) { diff --git a/src/admin/web/vhosts/balancing.js b/src/admin/web/vhosts/balancing.js new file mode 100644 index 0000000..27622bd --- /dev/null +++ b/src/admin/web/vhosts/balancing.js @@ -0,0 +1,255 @@ +// Load-balancing editor (vhost and location) with a consistent-hash distribution +// simulator. The pure helpers at the top mirror src/balance/model.rs (rendezvous +// scoring and hash keys) and are checked by tools/dev/test_balance_simulator.js. +const lbSha256 = (() => { + const K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]); + return bytes => { + const length = bytes.length, total = ((length + 9 + 63) >> 6) << 6, data = new Uint8Array(total); + data.set(bytes); data[length] = 0x80; + const view = new DataView(data.buffer); view.setUint32(total - 8, Math.floor(length / 0x20000000)); view.setUint32(total - 4, (length << 3) >>> 0); + const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]), w = new Uint32Array(64); + const rotr = (x, n) => (x >>> n) | (x << (32 - n)); + for (let offset = 0; offset < total; offset += 64) { + for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4); + for (let i = 16; i < 64; i++) { + const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3), s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10); + w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0; + } + let [a, b, c, d, e, f, g, hh] = h; + for (let i = 0; i < 64; i++) { + const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0; + const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0; + hh = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0; + } + h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; + } + const out = new Uint8Array(32), outView = new DataView(out.buffer); h.forEach((value, i) => outView.setUint32(i * 4, value)); return out; + }; +})(); +const lbEncoder = new TextEncoder(); +const LB_U64_SPAN = Number(2n ** 64n - 1n) + 2, LB_MIN_POSITIVE = 2.2250738585072014e-308; +// Same as rendezvous_score() in src/balance/model.rs: lowest score wins. +function lbScore(poolId, key, memberId, weight) { + const digest = lbSha256(lbEncoder.encode(`${poolId}|${key}|${memberId}`)); + let n = 0n; for (let i = 0; i < 8; i++) n = (n << 8n) | BigInt(digest[i]); + const unit = (Number(n) + 1) / LB_U64_SPAN; + return -Math.log(Math.max(unit, LB_MIN_POSITIVE)) / Math.max(1, Number(weight) || 1); +} +function lbRank(poolId, key, members) { + return members.map(member => ({ member, score: lbScore(poolId, key, member.id, member.weight) })).sort((a, b) => a.score - b.score).map(item => item.member); +} +function lbPathDepth(path, depth) { + if (!depth) return path; let seen = 0; + for (let i = 1; i < path.length; i++) if (path[i] === "/" && ++seen === depth) return path.slice(0, i); + return path; +} +// Parses one simulator sample: "/path?query", "https://host/path?query" or "host/path". +function lbParseSample(line) { + let rest = line.trim(), host = ""; + const scheme = rest.match(/^[a-z][a-z0-9+.-]*:\/\//i); + if (scheme) { rest = rest.slice(scheme[0].length); const slash = rest.search(/[/?]/); host = slash < 0 ? rest : rest.slice(0, slash); rest = slash < 0 ? "/" : rest.slice(slash); } + else if (!rest.startsWith("/")) { const slash = rest.search(/[/?]/); host = slash < 0 ? rest : rest.slice(0, slash); rest = slash < 0 ? "/" : rest.slice(slash); } + if (rest.startsWith("?")) rest = `/${rest}`; + const mark = rest.indexOf("?"); + const bracketed = host.match(/^\[([^\]]*)\]/); + host = bracketed ? bracketed[1] : host.includes(":") && host.indexOf(":") === host.lastIndexOf(":") ? host.replace(/:\d*$/, "") : host; + return { host: host.replace(/\.$/, "").toLowerCase(), path: mark < 0 ? rest : rest.slice(0, mark), query: mark < 0 ? null : rest.slice(mark + 1) }; +} +// Mirrors HashSettings::key(); header/cookie/IP samples are the raw value itself. +function lbHashKey(settings, line) { + const source = settings.source || "path", value = String(line).trim(); if (!value) return null; + if (source === "ip") return value; + let key; + if (["header", "cookie"].includes(source)) key = value; + else { + const sample = lbParseSample(value), depth = Number(settings.path_depth) || 0; + if (source === "host") return sample.host || null; + if (source === "path") key = lbPathDepth(sample.path, depth); + else if (source === "uri") key = lbPathDepth(sample.path, depth) + (sample.query !== null ? `?${sample.query}` : ""); + else if (source === "query") { + if (sample.query === null) return null; + const pair = sample.query.split("&").map(item => { const at = item.indexOf("="); return at < 0 ? [item, ""] : [item.slice(0, at), item.slice(at + 1)]; }).find(([name]) => name === settings.name); + key = pair?.[1] || null; + } + } + if (!key) return null; + return settings.ignore_case ? key.toLowerCase() : key; +} +// Which members a request may use (mirrors candidates: enabled, not draining, backups +// only when no primary is left). +function lbEligible(members, explicit, down = new Set()) { + const usable = members.filter(m => m.enabled && !m.drain && (explicit || m.pool_eligible) && !down.has(m.id)); + return usable.some(m => !m.backup) ? usable.filter(m => !m.backup) : usable; +} +function lbSimulate({ poolId, settings, members, explicit = false, samples, down = new Set() }) { + const before = lbEligible(members, explicit), after = lbEligible(members, explicit, down); + return samples.map(sample => { + const key = lbHashKey(settings, sample); + if (key === null) return { sample, key, member: null, previous: null }; + return { sample, key, previous: lbRank(poolId, key, before)[0]?.id || null, member: lbRank(poolId, key, after)[0]?.id || null }; + }); +} +if (typeof window !== "undefined") window.rustProxyBalancingCore = { sha256: lbSha256, score: lbScore, rank: lbRank, hashKey: lbHashKey, simulate: lbSimulate, eligible: lbEligible }; + +const LB_ALGORITHMS = [["round_robin", "vhRoundRobin"], ["least_connections", "vhLeastConnections"], ["least_traffic", "vhLeastTraffic"], ["adaptive", "vhAdaptive"], ["random", "lbRandom"], ["hash", "lbHash"], ["ip_hash", "vhIpHash"]]; +const LB_SOURCES = [["path", "lbSourcePath"], ["uri", "lbSourceUri"], ["host", "lbSourceHost"], ["header", "lbSourceHeader"], ["cookie", "lbSourceCookie"], ["query", "lbSourceQuery"], ["ip", "lbSourceIp"]]; +const LB_FALLBACKS = [["round_robin", "vhRoundRobin"], ["least_connections", "vhLeastConnections"], ["random", "lbRandom"]]; +const LB_PRESETS = [ + { key: "lbPresetFiles", algorithm: "hash", hash: { source: "path", ignore_case: true }, samples: "/media/intro.mp3\n/media/album/01.mp3\n/media/album/02.mp3\n/video/teaser.mp4\n/img/cover.jpg\n/media/album/03.mp3" }, + { key: "lbPresetCookie", algorithm: "hash", hash: { source: "cookie", name: "session" }, samples: "u-1001\nu-1002\nu-1003\nu-1004\nu-1005" }, + { key: "lbPresetTenant", algorithm: "hash", hash: { source: "header", name: "X-Tenant" }, samples: "acme\nglobex\ninitech\numbrella" }, + { key: "lbPresetQuery", algorithm: "hash", hash: { source: "query", name: "id" }, samples: "/api/items?id=1\n/api/items?id=2\n/api/items?id=3\n/api/items" }, + { key: "lbPresetIp", algorithm: "hash", hash: { source: "ip" }, samples: "203.0.113.10\n203.0.113.11\n198.51.100.7\n2001:db8::42" }, + { key: "lbPresetEven", algorithm: "least_connections", hash: {} } +]; +// HAProxy-style one-liner describing the configuration (helps people migrating). +function lbHaproxyLine(algorithm, hash) { + const map = { round_robin: "balance roundrobin", least_connections: "balance leastconn", random: "balance random(2)", ip_hash: "balance source\nhash-type consistent" }; + if (map[algorithm]) return map[algorithm]; + if (algorithm !== "hash") return ""; + const depth = Number(hash.path_depth) ? ` depth ${hash.path_depth}` : ""; + const lower = hash.ignore_case ? ",lower" : ""; + const source = { path: depth ? `balance uri path-only${depth}` : `balance hash path${lower}`, uri: `balance uri whole${depth}`, host: "balance hdr(host) use-domain-only", header: `balance hdr(${hash.name || "?"})`, cookie: `balance hash req.cook(${hash.name || "?"})`, query: `balance url_param ${hash.name || "?"}`, ip: "balance source" }[hash.source || "path"]; + return `${source}\nhash-type consistent${Number(hash.balance_factor) ? `\nhash-balance-factor ${hash.balance_factor}` : ""}`; +} + +// Balancing editor. options: { names: input name prefix, value: {algorithm, hash, sticky}, +// members(): [{id, weight, enabled, drain, backup, pool_eligible}], explicit(): bool, +// poolId(): string, stickyField: include a location affinity select, onChange() }. +function balancingEditor(parent, options) { + const value = options.value || {}, hash = { ...(value.hash || {}) }, prefix = options.names; + const box = el("div", undefined, "vh-wide lb-editor"); parent.append(box); + const presets = el("div", undefined, "lb-presets"); presets.append(text("span", "lbPresets", "lb-presets-label")); box.append(presets); + const grid = el("div", undefined, "vh-grid"); box.append(grid); + const algorithm = field(grid, `${prefix}algorithm`, "vhAlgorithm", value.algorithm || "least_connections", "select", { values: LB_ALGORITHMS }); + const sticky = options.stickyField ? field(grid, `${prefix}sticky`, "lbLocationSticky", value.sticky || "off", "select", { values: [["off", "vhOff"], ["cookie", "vhCookie"], ["ip_hash", "vhIpHash"]] }) : null; + const description = el("p", "", "fine vh-wide lb-description"); grid.append(description); + const hashBox = el("div", undefined, "vh-wide vh-grid lb-hash"); grid.append(hashBox); + const source = field(hashBox, `${prefix}hash-source`, "lbHashSource", hash.source || "path", "select", { values: LB_SOURCES }); + const name = field(hashBox, `${prefix}hash-name`, "lbHashName", hash.name || "", "text", { maxLength: 128 }); + const depth = field(hashBox, `${prefix}hash-depth`, "lbHashDepth", hash.path_depth ?? 0, "number", { min: 0, max: 32, step: 1 }); + const factor = field(hashBox, `${prefix}hash-factor`, "lbHashFactor", hash.balance_factor ?? 0, "number", { min: 0, max: 1000, step: 1 }); + const fallback = field(hashBox, `${prefix}hash-fallback`, "lbHashFallback", hash.fallback || "round_robin", "select", { values: LB_FALLBACKS }); + const ignoreCase = field(hashBox, `${prefix}hash-case`, "lbHashIgnoreCase", hash.ignore_case === true, "checkbox", { switch: true }); + const keyHelp = el("p", "", "fine vh-wide lb-key-help"); hashBox.append(keyHelp); + const equivalent = el("div", undefined, "vh-wide lb-equivalent"); const equivalentCode = el("pre", ""); equivalent.append(text("span", "lbHaproxyEquivalent"), equivalentCode); grid.append(equivalent); + + const simulator = el("details", undefined, "vh-wide lb-simulator"); simulator.append(text("summary", "lbSimulator")); box.append(simulator); + const simBody = el("div", undefined, "lb-sim-body"); simulator.append(simBody); + const simInputs = el("div", undefined, "lb-sim-inputs"); simBody.append(simInputs); + const sampleLabel = el("label", undefined, "vh-field lb-sim-samples"), sampleTitle = el("span", ""), samples = document.createElement("textarea"); + samples.rows = 7; samples.spellcheck = false; samples.maxLength = 20000; samples.value = options.samples || "/media/intro.mp3\n/media/album/01.mp3\n/media/album/02.mp3\n/img/cover.jpg"; + sampleLabel.append(sampleTitle, samples); simInputs.append(sampleLabel); + const downBox = el("div", undefined, "lb-sim-down"); downBox.append(text("span", "lbSimulateDown")); const downList = el("div", undefined, "lb-sim-down-list"); downBox.append(downList); simInputs.append(downBox); + const simOut = el("div", undefined, "lb-sim-out"); simBody.append(simOut); + const down = new Set(); + + const readHash = () => { + const result = { source: source.value }; + if (["header", "cookie", "query"].includes(source.value)) result.name = name.value.trim(); + if (["path", "uri"].includes(source.value) && Number(depth.value) > 0) result.path_depth = Number(depth.value); + if (ignoreCase.checked && source.value !== "ip" && source.value !== "host") result.ignore_case = true; + if (Number(factor.value) > 0) result.balance_factor = Number(factor.value); + if (fallback.value !== "round_robin") result.fallback = fallback.value; + return result; + }; + const members = () => (options.members() || []).filter(m => m.id); + const renderDown = () => { + const explicit = options.explicit?.() === true, list = members().filter(m => explicit || m.pool_eligible); + for (const id of [...down]) if (!list.some(m => m.id === id)) down.delete(id); + downList.replaceChildren(...list.map(member => { + const label = el("label", undefined, "check lb-sim-member"), box = document.createElement("input"); box.type = "checkbox"; box.checked = down.has(member.id); + box.addEventListener("change", () => { if (box.checked) down.add(member.id); else down.delete(member.id); simulate(); }); + box.setAttribute("aria-label", `${t("lbSimulateDown")}: ${member.id}`); + label.append(box, el("span", member.id)); return label; + })); + }; + const simulate = () => { + simOut.replaceChildren(); + const list = members(), explicit = options.explicit?.() === true, eligible = lbEligible(list, explicit); + if (!eligible.length) { simOut.append(text("p", "lbSimNoMembers", "fine")); return; } + if (algorithm.value !== "hash" && algorithm.value !== "ip_hash") { + const total = eligible.reduce((sum, m) => sum + Math.max(1, Number(m.weight) || 1), 0); + simOut.append(text("p", "lbSimLoadBased", "fine")); + simOut.append(lbBars(eligible.map(m => [m.id, Math.max(1, Number(m.weight) || 1) / total]))); + return; + } + const settings = algorithm.value === "ip_hash" ? { source: "ip" } : readHash(); + const lines = samples.value.split("\n").map(line => line.trim()).filter(Boolean).slice(0, 500); + const rows = lbSimulate({ poolId: options.poolId() || "vhost", settings, members: list, explicit, samples: lines, down }); + const counts = new Map(eligible.filter(m => !down.has(m.id)).map(m => [m.id, 0])); + const table = el("table", undefined, "lb-sim-table"), head = el("tr"); + for (const key of ["lbSimRequest", "lbSimKey", "backend"]) head.append(text("th", key)); + table.append(head); + let moved = 0, fallbackRows = 0; + for (const row of rows) { + const tr = el("tr"), keyCell = el("td"), target = el("td"); + tr.append(el("td", row.sample)); + if (row.key === null) { fallbackRows++; keyCell.append(text("em", "lbSimNoKey")); target.textContent = `${t("lbSimFallback")}: ${t(LB_FALLBACKS.find(([v]) => v === (settings.fallback || "round_robin"))?.[1] || "vhRoundRobin")}`; tr.classList.add("is-fallback"); } + else { + keyCell.append(el("code", row.key)); + target.append(el("strong", row.member || "-")); + if (row.member) counts.set(row.member, (counts.get(row.member) || 0) + 1); + if (row.previous && row.member !== row.previous) { moved++; tr.classList.add("is-moved"); target.append(el("span", ` ← ${row.previous}`, "lb-moved")); } + } + tr.append(keyCell, target); table.append(tr); + } + const hashed = rows.length - fallbackRows; + simOut.append(lbBars([...counts].map(([id, count]) => [id, hashed ? count / hashed : 0, count]))); + const summary = el("p", "", "fine lb-sim-summary"); + summary.textContent = down.size ? t("lbSimMoved").replace("{moved}", String(moved)).replace("{total}", String(hashed)) : t("lbSimStable"); + simOut.append(summary, table); + }; + const lbBars = entries => { + const bars = el("div", undefined, "lb-bars"); + for (const [id, share, count] of entries) { + const row = el("div", undefined, "lb-bar"), track = el("span", undefined, "lb-bar-track"), fill = el("span", undefined, "lb-bar-fill"); + fill.style.width = `${Math.round(share * 100)}%`; track.append(fill); + row.append(el("span", id, "lb-bar-label"), track, el("span", `${Math.round(share * 100)}%${count !== undefined ? ` · ${count}` : ""}`, "lb-bar-value")); bars.append(row); + } + return bars; + }; + const sync = () => { + const isHash = algorithm.value === "hash", needsName = ["header", "cookie", "query"].includes(source.value); + hashBox.hidden = !isHash; + for (const [control, show] of [[name, needsName], [depth, ["path", "uri"].includes(source.value)], [ignoreCase, !["ip", "host"].includes(source.value)], [fallback, source.value !== "ip"]]) { control.closest("label").hidden = !show; control.disabled = !isHash || !show; } + name.required = isHash && needsName; + name.placeholder = { header: "X-Tenant", cookie: "session", query: "id" }[source.value] || ""; + description.textContent = t(`lbDescribe_${algorithm.value}`); + keyHelp.textContent = t(`lbKeyHelp_${source.value}`); + sampleTitle.textContent = t(algorithm.value === "hash" && ["header", "cookie", "ip"].includes(source.value) ? `lbSimSamples_${source.value}` : algorithm.value === "ip_hash" ? "lbSimSamples_ip" : "lbSimSamples"); + const line = lbHaproxyLine(algorithm.value, readHash()); equivalent.hidden = !line; equivalentCode.textContent = line; + renderDown(); if (simulator.open) simulate(); + }; + for (const preset of LB_PRESETS) { + presets.append(button(preset.key, () => { + algorithm.value = preset.algorithm; source.value = preset.hash.source || "path"; name.value = preset.hash.name || ""; depth.value = 0; factor.value = 0; fallback.value = "round_robin"; ignoreCase.checked = preset.hash.ignore_case === true; + if (preset.samples) samples.value = preset.samples; + sync(); simulator.open = preset.algorithm === "hash"; if (simulator.open) simulate(); options.onChange?.(); + }, "quiet lb-preset")); + } + // The simulator is a scratch pad: its inputs never mark the vhost as changed. + for (const type of ["input", "change"]) simulator.addEventListener(type, event => { event.stopPropagation(); if (event.target === samples) simulate(); }); + box.addEventListener("input", () => { sync(); options.onChange?.(); }); + box.addEventListener("change", () => { sync(); options.onChange?.(); }); + simulator.addEventListener("toggle", () => { if (simulator.open) { renderDown(); simulate(); } }); + sync(); + return { + algorithm: () => algorithm.value, + hash: () => algorithm.value === "hash" ? readHash() : undefined, + sticky: () => sticky?.value || "off", + refresh: sync, + validate() { if (algorithm.value === "hash" && ["header", "cookie", "query"].includes(source.value) && !name.value.trim()) throw new Error(t("lbHashNameRequired")); } + }; +} +// Reads the vhost backend rows for the balancing editors and simulators. +function balancingMembers() { + return [...form.querySelectorAll(".vh-member")].map(row => ({ + id: str("member-id", row), weight: Number(str("member-weight", row)) || 1, + enabled: yes("member-enabled", row), drain: yes("member-drain", row), backup: yes("member-backup", row), pool_eligible: yes("member-pool", row) + })); +} diff --git a/src/admin/web/vhosts/core.js b/src/admin/web/vhosts/core.js index 0ed8014..8f737e2 100644 --- a/src/admin/web/vhosts/core.js +++ b/src/admin/web/vhosts/core.js @@ -1,6 +1,6 @@ "use strict"; let vhostCacheRulesEditor = null; -let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null; +let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null; const chartHistory = new Map(); const backendTrafficHistory = new Map(); const backendRequestHistory = new Map(); @@ -345,22 +345,31 @@ function openLocationHelp(topic = "locations") { } dialog.showModal(); } +const LOCATION_GROUP = "__group__"; function locationsEditor(parent, values) { const toolbar = el("div", undefined, "vh-wide location-toolbar"), rows = el("div", undefined, "vh-wide vh-locations"); const addTop = button("locationAdd", () => { add(); sync(); }, "primary"); - toolbar.append(addTop, button("documentation", () => openLocationHelp("locations"))); - parent.append(toolbar); note(parent, "locationHelp"); parent.append(rows); let reloading = false; + const addHostRule = button("rtAddHostRule", () => { add({ id: nextId("host-rule"), match_type: "any", conditions: [{ source: "header", name: "", operator: "equals", values: [] }] }, true); sync(); }); + toolbar.append(addTop, addHostRule, button("documentation", () => openLocationHelp("locations"))); + parent.append(toolbar); note(parent, "locationHelp"); note(parent, "rtOrderHelp"); + const tester = routingTester(parent, () => readRows()); + parent.append(rows); let reloading = false; + const nextId = base => { const used = new Set([...rows.children].map(r => str("location-id", r))); let n = 1; while (used.has(`${base}-${n}`)) n++; return `${base}-${n}`; }; function readRows() { return [...rows.children].map(r => { const action = str("location-action", r), rewriteMode = str("location-rewrite-mode", r); const handled = action === "proxy" || action === "web_server"; const internal = yes("location-internal", r), fallbackTarget = str("location-error-target", r); const fallbackStatuses = lines(str("location-error-statuses", r)).map(value => Number(value)); + const matchType = internal ? "prefix" : str("location-match", r), conditions = internal ? [] : r.readConditions(); return { - id: str("location-id", r), internal, path_prefix: internal ? "/" : str("location-path", r), match_type: internal ? "prefix" : str("location-match", r), + id: str("location-id", r), internal, path_prefix: internal || matchType === "any" ? "/" : str("location-path", r), match_type: matchType, + ...(conditions.length ? { conditions } : {}), source: action === "web_server" ? { type: "web_server", web_service_id: str("location-web-service", r) } : { type: "reverse_proxy" }, - backend_id: action === "proxy" ? (str("location-backend", r) || null) : null, - enabled: yes("location-enabled", r), cache: action === "proxy" ? (str("location-cache", r) === "" ? null : str("location-cache", r) === "on") : false, + backend_id: action === "proxy" && !["", LOCATION_GROUP].includes(str("location-backend", r)) ? str("location-backend", r) : null, + backend_ids: action === "proxy" && str("location-backend", r) === LOCATION_GROUP ? r.groupIds() : [], + load_balancing: action === "proxy" && ["", LOCATION_GROUP].includes(str("location-backend", r)) ? r.readBalancing() : null, + enabled: yes("location-enabled", r), cache: action === "proxy" && !conditions.length ? (str("location-cache", r) === "" ? null : str("location-cache", r) === "on") : conditions.length ? null : false, acl_profile_id: str("location-acl-profile", r) || null, acl: r.readAcl(), country_access: { mode: str("location-country-mode", r), countries: lines(str("location-country-list", r)).map(value => value.toUpperCase()) }, @@ -373,24 +382,57 @@ function locationsEditor(parent, values) { }; }); } - function sync() { if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); changed(); } catch { } } - function memberOptions(select, chosen = select.value) { const base = text("option", "locationPool"); base.value = ""; select.replaceChildren(base, ...[...form.querySelectorAll(".vh-member")].map(m => { const id = str("member-id", m), o = el("option", `${id} / ${str("member-url", m)}`); o.value = id; return o; })); if (chosen && !Array.from(select.options).some(o => o.value === chosen)) { const o = el("option", `${chosen} / ${t("locationMissing")}`); o.value = chosen; select.append(o); } select.value = chosen; } - function add(value = {}) { + function sync() { if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); changed(); } catch { } tester?.run(); } + function memberOptions(select, chosen = select.value) { const base = text("option", "locationPool"); base.value = ""; const groupOption = text("option", "locationBackendGroup"); groupOption.value = LOCATION_GROUP; select.replaceChildren(base, groupOption, ...[...form.querySelectorAll(".vh-member")].map(m => { const id = str("member-id", m), o = el("option", `${id} / ${str("member-url", m)}`); o.value = id; return o; })); if (chosen && !Array.from(select.options).some(o => o.value === chosen)) { const o = el("option", `${chosen} / ${t("locationMissing")}`); o.value = chosen; select.append(o); } select.value = chosen; } + function add(value = {}, openConditions = false) { if (rows.children.length >= 64) { toast(t("locationLimit"), true); return; } const row = el("details", undefined, "vh-location"); row.open = true; const summary = el("summary", undefined, "location-summary"), body = el("div", undefined, "vh-grid location-body"); row.append(summary, body); const used = new Set([...rows.children].map(r => str("location-id", r))); let suffix = 1; while (used.has(`location-${suffix}`)) suffix++; field(body, "location-id", "locationId", value.id || `location-${suffix}`, "text", { required: true, pattern: "[A-Za-z0-9_\\-]{1,64}", maxLength: 64 }); - const match = field(body, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"]] }); + const match = field(body, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"], ["any", "locationMatchAny"]] }); const path = field(body, "location-path", "locationPathPattern", value.path_prefix || "/", "text", { required: true, maxLength: 1024 }); path.placeholder = "/api or ^/api/v[0-9]+/"; const internal = field(body, "location-internal", "locationInternal", value.internal === true, "checkbox", { switch: true }); const initialAction = value.response ? "return" : value.redirect ? "redirect" : value.source?.type === "web_server" ? "web_server" : "proxy"; const action = field(body, "location-action", "locationAction", initialAction, "select", { values: [["proxy", "locationProxyAction"], ["web_server", "locationWebServerAction"], ["redirect", "locationRedirectAction"], ["return", "locationReturnAction"]] }); - const backend = field(body, "location-backend", "backend", value.backend_id || "", "select"); memberOptions(backend, value.backend_id || ""); + const initialTarget = value.backend_ids?.length ? LOCATION_GROUP : value.backend_id || ""; + const backend = field(body, "location-backend", "locationTarget", initialTarget, "select"); memberOptions(backend, initialTarget); const webService = field(body, "location-web-service", "webService", value.source?.web_service_id || "", "select"); fillWebServices(webService, value.source?.web_service_id || ""); field(body, "location-enabled", "enabled", value.enabled !== false, "checkbox", { switch: true }); const cache = field(body, "location-cache", "cacheEnabled", value.cache === true ? "on" : value.cache === false ? "off" : "", "select", { values: [["", "inherit"], ["on", "enabled"], ["off", "notEnabled"]] }); + const conditionBox = el("details", undefined, "vh-wide location-section location-conditions"), conditionBody = el("div", undefined, "vh-grid"); conditionBox.append(text("summary", "rtConditions"), conditionBody); body.append(conditionBox); + conditionBox.open = openConditions || Boolean(value.conditions?.length); + note(conditionBody, "rtConditionsHelp"); + const conditions = conditionsEditor(conditionBody, value.conditions || [], () => { syncUi(); sync(); }); row.readConditions = conditions.read; + const conditionCacheNote = text("p", "rtNotCachedHelp", "fine vh-wide"); conditionBody.append(conditionCacheNote); + const balancing = el("details", undefined, "vh-wide location-section location-balancing"), balancingBody = el("div", undefined, "vh-grid"); balancing.append(text("summary", "locationBalancing"), balancingBody); body.append(balancing); + balancing.open = Boolean(value.backend_ids?.length || value.load_balancing); + const groupBox = el("div", undefined, "vh-wide location-group"); groupBox.append(text("span", "locationGroupMembers", "location-group-title")); + const groupList = el("div", undefined, "location-group-list"); groupBox.append(groupList, text("p", "locationGroupHelp", "fine")); balancingBody.append(groupBox); + const groupSelected = new Set(value.backend_ids || []); + const renderGroup = () => { + const all = balancingMembers(); for (const id of [...groupSelected]) if (!all.some(m => m.id === id)) groupSelected.delete(id); + groupList.replaceChildren(...all.filter(m => m.id).map(member => { + const label = el("label", undefined, "check location-group-member"), box = document.createElement("input"); box.type = "checkbox"; box.checked = groupSelected.has(member.id); + box.addEventListener("change", () => { if (box.checked) groupSelected.add(member.id); else groupSelected.delete(member.id); balancingControl.refresh(); }); + const tags = [member.pool_eligible ? "" : t("locationOnlyTag"), member.backup ? t("vhBackup") : "", member.enabled ? "" : t("vhOff")].filter(Boolean).join(" · "); + label.append(box, el("span", member.id), el("small", tags ? ` ${tags}` : "", "fine")); return label; + })); + }; + row.groupIds = () => { const ids = balancingMembers().map(m => m.id).filter(id => groupSelected.has(id)); if (!ids.length) throw new Error(t("locationGroupEmpty").replace("{location}", str("location-id", row))); return ids; }; + backend.addEventListener("change", () => { if (backend.value === LOCATION_GROUP) balancing.open = true; }); + const ownBalancing = field(balancingBody, "location-lb-custom", "lbLocationOwn", Boolean(value.load_balancing), "checkbox", { switch: true }); + const balancingSlot = el("div", undefined, "vh-wide vh-grid"); balancingBody.append(balancingSlot); + const balancingControl = balancingEditor(balancingSlot, { + names: "location-lb-", value: value.load_balancing || { algorithm: "hash", hash: { source: "path" } }, stickyField: true, + members: () => backend.value === LOCATION_GROUP ? balancingMembers().filter(m => groupSelected.has(m.id)) : balancingMembers(), + explicit: () => backend.value === LOCATION_GROUP, poolId: () => str("id"), onChange: sync + }); + const inheritNote = text("p", "lbLocationInherit", "fine vh-wide"); balancingBody.append(inheritNote); + row.readBalancing = () => { if (!ownBalancing.checked) return null; balancingControl.validate(); const hash = balancingControl.hash(); return { algorithm: balancingControl.algorithm(), ...(hash ? { hash } : {}), sticky: balancingControl.sticky() }; }; + row.refreshBalancing = () => { renderGroup(); balancingControl.refresh(); }; + renderGroup(); const handling = el("details", undefined, "vh-wide location-section"), handlingBody = el("div", undefined, "vh-grid"); handling.append(text("summary", "locationHandling"), handlingBody); body.append(handling); field(handlingBody, "location-error-target", "locationErrorFallbackTarget", value.error_fallback?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" }); field(handlingBody, "location-error-statuses", "locationErrorFallbackStatuses", (value.error_fallback?.statuses || [404]).join(", "), "text", { maxLength: 64 }); @@ -442,23 +484,32 @@ function locationsEditor(parent, values) { preview.append(previewGrid); body.append(preview); const actions = el("div", undefined, "vh-wide location-actions"); - const dedicated = button("locationAddBackend", () => { const members = form.querySelector(".vh-members"); let i = 1; const ids = new Set([...members.children].map(r => str("member-id", r))); while (ids.has(`location-origin-${i}`)) i++; const id = `location-origin-${i}`; memberRow(members, { id, url: "http://127.0.0.1:9001", weight: 1, enabled: true, pool_eligible: false, allow_private: false }); memberOptions(backend, id); sync(); activateTab("backends"); }); - actions.append(dedicated, button("remove", () => { row.remove(); sync(); })); body.append(actions); + const dedicated = button("locationAddBackend", () => { const members = form.querySelector(".vh-members"); let i = 1; const ids = new Set([...members.children].map(r => str("member-id", r))); while (ids.has(`location-origin-${i}`)) i++; const id = `location-origin-${i}`; memberRow(members, { id, url: "http://127.0.0.1:9001", weight: 1, enabled: true, pool_eligible: false, allow_private: false }); if (backend.value === LOCATION_GROUP) { groupSelected.add(id); memberOptions(backend, LOCATION_GROUP); row.refreshBalancing(); } else memberOptions(backend, id); sync(); activateTab("backends"); }); + const moveUp = button("rtMoveUp", () => { if (row.previousElementSibling) { rows.insertBefore(row, row.previousElementSibling); sync(); } }); + const moveDown = button("rtMoveDown", () => { if (row.nextElementSibling) { rows.insertBefore(row.nextElementSibling, row); sync(); } }); + actions.append(moveUp, moveDown, dedicated, button("remove", () => { row.remove(); sync(); })); body.append(actions); const syncUi = () => { const isReturn = action.value === "return", isRedirect = action.value === "redirect", isWeb = action.value === "web_server", isProxy = action.value === "proxy", isRegex = match.value === "regex" || match.value === "regex_insensitive"; - match.disabled = path.disabled = internal.checked; - backend.disabled = !isProxy; cache.disabled = !isProxy; dedicated.disabled = !isProxy; + match.disabled = internal.checked; path.disabled = internal.checked || match.value === "any"; + const conditional = !internal.checked && conditions.count() > 0; + conditionBox.hidden = internal.checked; conditionCacheNote.hidden = !conditional; + if (conditional) cache.value = ""; + backend.disabled = !isProxy; cache.disabled = !isProxy || conditional; dedicated.disabled = !isProxy; + const isGroup = isProxy && backend.value === LOCATION_GROUP, pinned = isProxy && !["", LOCATION_GROUP].includes(backend.value); + balancing.hidden = !isProxy || pinned; groupBox.hidden = !isGroup; + ownBalancing.disabled = !isProxy || pinned; balancingSlot.hidden = !ownBalancing.checked; inheritNote.hidden = ownBalancing.checked; webService.disabled = !isWeb; webService.required = isWeb; returnBox.hidden = !isReturn; redirectBox.hidden = !isRedirect; rewriteMode.disabled = isReturn || isRedirect; rewriteValue.disabled = isReturn || isRedirect || rewriteMode.value === "preserve" || rewriteMode.value === "strip_prefix"; for (const option of rewriteMode.options) if (option.value === "regex") option.disabled = !isRegex; if (!isRegex && rewriteMode.value === "regex") rewriteMode.value = "preserve"; path.placeholder = isRegex ? "^/api/v[0-9]+/" : "/api/"; - const id = str("location-id", row) || t("locationId"), pattern = internal.checked ? `@${id}` : (str("location-path", row) || "/"); - summary.textContent = `${id} · ${internal.checked ? t("locationInternal") : t(`locationMatch_${match.value}`)} · ${pattern} · ${t(isReturn ? "locationReturnShort" : isRedirect ? "locationRedirectShort" : isWeb ? "locationWebServerShort" : "locationProxyShort")}`; + const id = str("location-id", row) || t("locationId"), pattern = internal.checked ? `@${id}` : match.value === "any" ? "*" : (str("location-path", row) || "/"); + const conditionNote = conditional ? ` · ${t("rtConditionCount").replace("{count}", String(conditions.count()))}` : ""; + summary.textContent = `${id} · ${internal.checked ? t("locationInternal") : t(`locationMatch_${match.value}`)} · ${pattern} · ${t(isReturn ? "locationReturnShort" : isRedirect ? "locationRedirectShort" : isWeb ? "locationWebServerShort" : "locationProxyShort")}${conditionNote}`; previewStatus.hidden = yes("location-enabled", row); - previewValues.match.textContent = `${t(`locationMatch_${match.value}`)} · ${pattern}`; + previewValues.match.textContent = `${t(`locationMatch_${match.value}`)} · ${pattern}${conditionNote}`; if (isReturn) { const status = str("location-response-status", row) || "200", type = str("location-response-type", row) || "text/plain"; previewValues.handling.textContent = `${t("locationReturnAction")}: HTTP ${status} · ${type} · ${t("locationPreviewBackendSkipped")}`; @@ -475,8 +526,9 @@ function locationsEditor(parent, values) { previewValues.handling.textContent = `${t("locationWebServerAction")}: ${selected}`; previewValues.cache.textContent = t("notEnabled"); } else { - const selected = backend.selectedOptions?.[0]?.textContent || t("locationPool"); - previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}`; + const selected = backend.value === LOCATION_GROUP ? `${t("locationBackendGroup")} (${[...groupSelected].join(", ") || "-"})` : backend.selectedOptions?.[0]?.textContent || t("locationPool"); + const algorithmLabel = ownBalancing.checked && !balancing.hidden ? ` · ${t(LB_ALGORITHMS.find(([v]) => v === balancingControl.algorithm())?.[1] || "vhAlgorithm")}${balancingControl.algorithm() === "hash" ? ` (${t(LB_SOURCES.find(([v]) => v === balancingControl.hash().source)?.[1] || "lbHash")})` : ""}` : ""; + previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}${algorithmLabel}`; previewValues.cache.textContent = t(cache.value === "on" ? "enabled" : cache.value === "off" ? "notEnabled" : "inherit"); } const rewriteLabels = { preserve: "locationRewritePreserve", strip_prefix: "locationRewriteStrip", replace_prefix: "locationRewriteReplace", regex: "locationRewriteRegex" }; @@ -499,7 +551,8 @@ function locationsEditor(parent, values) { } for (const value of values) add(value); const bottom = el("div", undefined, "vh-wide location-toolbar location-toolbar-bottom"); bottom.append(button("locationAdd", () => { add(); sync(); }, "primary")); parent.append(bottom); - form.querySelector(".vh-members").addEventListener("input", () => { for (const select of rows.querySelectorAll('[name="location-backend"]')) memberOptions(select); }); + const refreshMembers = () => { for (const select of rows.querySelectorAll('[name="location-backend"]')) memberOptions(select); for (const row of rows.children) row.refreshBalancing?.(); }; + form.querySelector(".vh-members").addEventListener("input", refreshMembers); form.querySelector(".vh-members").addEventListener("change", refreshMembers); read("paths").addEventListener("change", () => { try { const data = JSON.parse(str("paths")); if (!Array.isArray(data) || data.length > 64) return; reloading = true; rows.replaceChildren(); for (const value of data) add(value); } catch { } finally { reloading = false; } }); sync(); return readRows; } diff --git a/src/admin/web/vhosts/editor.js b/src/admin/web/vhosts/editor.js index 9c640b9..59bf667 100644 --- a/src/admin/web/vhosts/editor.js +++ b/src/admin/web/vhosts/editor.js @@ -221,7 +221,8 @@ function load(value = defaults(), migrationIds = [], show = true) { const settings = value.load_balancing || {}, health = settings.health_check || {}, keepalive = settings.keepalive || {}, retry = settings.retry || {}, sticky = settings.sticky || {}; g = group("vhBalancing"); const schedulingFields = subsection(g, "vhBalancerAlgorithmSection"); - field(schedulingFields, "algorithm", "vhAlgorithm", settings.algorithm || "least_connections", "select", { values: [["round_robin", "vhRoundRobin"], ["least_connections", "vhLeastConnections"], ["least_traffic", "vhLeastTraffic"], ["adaptive", "vhAdaptive"], ["ip_hash", "vhIpHash"]] }); + vhostBalancingControl = balancingEditor(schedulingFields, { names: "", value: settings, members: balancingMembers, poolId: () => str("id"), onChange: changed }); + members.addEventListener("input", () => vhostBalancingControl?.refresh()); members.addEventListener("change", () => vhostBalancingControl?.refresh()); field(schedulingFields, "slow-start", "vhSlowStart", settings.slow_start_seconds ?? 10, "number", { required: true, min: 0, max: 300 }); const retryFields = subsection(g, "vhBalancerRetrySection"); field(retryFields, "retry-max", "vhRetryMax", retry.max_retries ?? 1, "number", { required: true, min: 0, max: 3 }); @@ -645,7 +646,7 @@ function collect() { timeout_seconds: num("oidc-timeout"), session_ttl_seconds: num("oidc-ttl") }, backends: members, routes: paths, acl, headers, load_balancing: { - algorithm: str("algorithm"), slow_start_seconds: num("slow-start"), keepalive: { enabled: yes("keepalive"), idle_timeout_seconds: num("idle-timeout"), max_idle_per_host: num("max-idle"), tcp_keepalive_seconds: num("tcp-keepalive"), pool_recycle_requests: num("pool-recycle-requests"), pool_recycle_seconds: num("pool-recycle-seconds"), http1_max_buffer_bytes: num("http1-max-buffer") }, + algorithm: str("algorithm"), ...(vhostBalancingControl?.hash() ? { hash: vhostBalancingControl.hash() } : {}), slow_start_seconds: num("slow-start"), keepalive: { enabled: yes("keepalive"), idle_timeout_seconds: num("idle-timeout"), max_idle_per_host: num("max-idle"), tcp_keepalive_seconds: num("tcp-keepalive"), pool_recycle_requests: num("pool-recycle-requests"), pool_recycle_seconds: num("pool-recycle-seconds"), http1_max_buffer_bytes: num("http1-max-buffer") }, retry: { max_retries: num("retry-max"), retry_connect_errors: yes("retry-connect"), retry_timeouts: yes("retry-timeouts"), retry_statuses: str("retry-statuses").split(/[\s,]+/).filter(Boolean).map(value => Number(value)) }, health_check: { mode: str("health-mode"), path: str("health-path"), host: nullable("health-host"), port: optionalPort("health-port"), expect_body: nullable("health-expect-body"), interval_ms: num("interval"), timeout_ms: num("timeout"), slow_response_ms: num("slow"), fall: num("fall"), rise: num("rise"), expected_status_min: num("status-min"), expected_status_max: num("status-max") }, passive_health: { diff --git a/src/admin/web/vhosts/routing.js b/src/admin/web/vhosts/routing.js new file mode 100644 index 0000000..26f8855 --- /dev/null +++ b/src/admin/web/vhosts/routing.js @@ -0,0 +1,227 @@ +// Location conditions editor and the routing tester. The pure helpers mirror +// src/config/snapshot.rs (select_route) and src/vhost/conditions.rs and are checked +// against tests/fixtures/routing_conditions_cases.json by tools/dev/test_routing_tester.js. +const RT_SOURCES = [["header", "rtSourceHeader"], ["cookie", "rtSourceCookie"], ["query", "rtSourceQuery"], ["method", "rtSourceMethod"], ["ip", "rtSourceIp"], ["host", "rtSourceHost"], ["country", "rtSourceCountry"]]; +const RT_OPERATORS = [["equals", "rtOpEquals"], ["exists", "rtOpExists"], ["prefix", "rtOpPrefix"], ["suffix", "rtOpSuffix"], ["contains", "rtOpContains"], ["regex", "rtOpRegex"], ["cidr", "rtOpCidr"]]; +function rtOperatorsFor(source) { + if (source === "ip") return ["cidr"]; + if (source === "method" || source === "country") return ["equals"]; + if (source === "host") return ["equals", "prefix", "suffix", "contains", "regex"]; + return ["equals", "exists", "prefix", "suffix", "contains", "regex"]; +} +// Rust regex → JS RegExp (common subset; a leading (?i) becomes the i flag). +function rtRegex(pattern, insensitive = false) { + let flags = insensitive ? "i" : "", body = pattern; + const inline = body.match(/^\(\?([imsx]+)\)/); + if (inline) { body = body.slice(inline[0].length); if (inline[1].includes("i")) flags += flags.includes("i") ? "" : "i"; if (inline[1].includes("s")) flags += "s"; if (inline[1].includes("m")) flags += "m"; } + return new RegExp(body, `${flags}u`); +} +function rtIpToBits(text) { + const value = String(text).trim(); + if (/^\d{1,3}(\.\d{1,3}){3}$/.test(value)) { + const parts = value.split(".").map(Number); if (parts.some(p => p > 255)) return null; + return { v6: false, bits: parts.reduce((acc, p) => (acc << 8n) | BigInt(p), 0n) }; + } + if (!value.includes(":")) return null; + let [head, tail] = value.split("::"); if (value.split("::").length > 2) return null; + const hextets = s => (s ? s.split(":") : []); + let left = hextets(head), right = tail === undefined ? [] : hextets(tail); + const last = (right.length ? right : left)[(right.length ? right : left).length - 1]; + const v4 = last && last.includes(".") ? rtIpToBits(last) : null; + if (v4) { const list = right.length ? right : left; list.pop(); list.push(((v4.bits >> 16n) & 0xffffn).toString(16), (v4.bits & 0xffffn).toString(16)); } + const fill = 8 - left.length - right.length; if (tail === undefined && fill !== 0) return null; if (fill < 0) return null; + const all = [...left, ...Array(tail === undefined ? 0 : fill).fill("0"), ...right]; + if (all.length !== 8 || all.some(h => !/^[0-9a-f]{1,4}$/i.test(h))) return null; + const bits = all.reduce((acc, h) => (acc << 16n) | BigInt(parseInt(h, 16)), 0n); + if (bits >> 32n === 0xffffn) return { v6: false, bits: bits & 0xffffffffn }; // IPv4-mapped, like canonical_ip() + return { v6: true, bits }; +} +function rtCidrContains(network, ip) { + const [addr, len] = String(network).trim().split("/"); const net = rtIpToBits(addr), target = rtIpToBits(ip); + if (!net || !target || net.v6 !== target.v6) return false; + const width = net.v6 ? 128 : 32, prefix = len === undefined ? width : Number(len); + if (!Number.isInteger(prefix) || prefix < 0 || prefix > width) return false; + const shift = BigInt(width - prefix); return (net.bits >> shift) === (target.bits >> shift); +} +function rtHeaderValues(request, name) { + const lower = name.toLowerCase(); return (request.headers || []).filter(([key]) => key.toLowerCase() === lower).map(([, value]) => value.trim()); +} +function rtConditionValues(condition, request) { + const name = (condition.name || "").trim(); + switch (condition.source) { + case "header": return rtHeaderValues(request, name); + case "cookie": return rtHeaderValues(request, "cookie").flatMap(v => v.split(";")).map(p => p.trim()).filter(p => p.includes("=")).map(p => [p.slice(0, p.indexOf("=")), p.slice(p.indexOf("=") + 1)]).filter(([n]) => n === name).map(([, v]) => v.trim()); + case "query": return request.query === null || request.query === undefined ? [] : request.query.split("&").map(p => p.includes("=") ? [p.slice(0, p.indexOf("=")), p.slice(p.indexOf("=") + 1)] : [p, ""]).filter(([n]) => n === name).map(([, v]) => v); + case "method": return [String(request.method || "GET").toUpperCase()]; + case "host": return [String(request.host || "").replace(/\.$/, "").toLowerCase()]; + case "country": return request.country ? [String(request.country).toUpperCase()] : []; + case "ip": return [String(request.client_ip || "")]; + default: return []; + } +} +// Mirrors CompiledCondition::matches(). Throws for patterns the browser cannot run. +function rtConditionMatches(condition, request) { + const op = condition.operator || "equals", source = condition.source || "header"; + const fold = (condition.ignore_case && ["header", "cookie", "query"].includes(source)) || source === "host"; + const values = (condition.values || []).map(v => String(v).trim()); + const raw = rtConditionValues(condition, request); + const norm = value => { + if (source === "method" || source === "country") return value.toUpperCase(); + if (source === "host") return value.replace(/\.$/, "").toLowerCase(); + return fold ? value.toLowerCase() : value; + }; + let hit; + if (op === "exists") hit = raw.length > 0; + else if (op === "cidr") hit = values.some(net => rtCidrContains(net, request.client_ip)); + else if (op === "regex") { const list = values.map(v => rtRegex(v, fold)); hit = raw.some(v => list.some(r => r.test(v))); } + else { + const patterns = values.map(norm), test = { equals: (v, p) => v === p, prefix: (v, p) => v.startsWith(p), suffix: (v, p) => v.endsWith(p), contains: (v, p) => v.includes(p) }[op]; + hit = raw.some(v => patterns.some(p => test(norm(v), p))); + } + return hit !== Boolean(condition.negate); +} +function rtNormalizePrefix(prefix) { let value = String(prefix || "/").trim(); if (!value.startsWith("/")) value = `/${value}`; if (value.length > 1) value = value.replace(/\/+$/, ""); return value || "/"; } +function rtPrefixMatches(prefix, path) { return prefix === "/" || path === prefix || path.startsWith(`${prefix}/`); } +// Evaluates every location like select_route() and returns the winner plus a trace. +function rtEvaluate(routes, request) { + const path = String(request.path || "/").replace(/%2f/gi, "/"); + const trace = routes.map((route, index) => { + const type = route.match_type || "prefix", internal = route.internal === true, enabled = route.enabled !== false; + let pathMatch = false, error = null; + try { + if (type === "exact") pathMatch = route.path_prefix === path; + else if (type === "prefix" || type === "prefix_priority") pathMatch = rtPrefixMatches(rtNormalizePrefix(route.path_prefix), path); + else if (type === "regex" || type === "regex_insensitive") pathMatch = rtRegex(route.path_prefix, type === "regex_insensitive").test(path); + else if (type === "any") pathMatch = true; + } catch (cause) { error = cause.message; } + const conditions = (route.conditions || []).map(condition => { try { return rtConditionMatches(condition, request); } catch (cause) { error = cause.message; return false; } }); + const usable = enabled && !internal && !error && conditions.every(Boolean); + return { route, index, type, pathMatch, conditions, usable, error, conditional: (route.conditions || []).length > 0, prefixLength: rtNormalizePrefix(route.path_prefix).length }; + }); + const ok = item => item.pathMatch && item.usable; + const exact = trace.filter(i => i.type === "exact" && ok(i)); + if (exact.length) return { winner: exact.find(i => i.conditional) || exact[0], trace }; + let prefix = null; + for (const item of trace) { + if (!["prefix", "prefix_priority"].includes(item.type) || !ok(item)) continue; + if (!prefix || item.prefixLength > prefix.prefixLength || (item.prefixLength === prefix.prefixLength && item.conditional && !prefix.conditional)) prefix = item; + } + if (prefix?.type === "prefix_priority") return { winner: prefix, trace }; + const regex = trace.find(i => ["regex", "regex_insensitive", "any"].includes(i.type) && ok(i)); + return { winner: regex || prefix || null, trace }; +} +if (typeof window !== "undefined") window.rustProxyRoutingCore = { evaluate: rtEvaluate, conditionMatches: rtConditionMatches, cidrContains: rtCidrContains }; + +// Editor for a location's conditions. Returns read() → array of conditions. +function conditionsEditor(parent, values = [], onChange = () => { }) { + const box = el("div", undefined, "vh-wide rt-conditions"), list = el("div", undefined, "rt-condition-list"); box.append(list); parent.append(box); + const empty = text("p", "rtNoConditions", "fine rt-empty"); box.prepend(empty); + const add = (value = { source: "header", operator: "equals", values: [] }) => { + if (list.children.length >= 16) { toast(t("rtTooMany"), true); return; } + const row = el("div", undefined, "rt-condition"); + const source = document.createElement("select"), name = document.createElement("input"), operator = document.createElement("select"), valuesInput = document.createElement("textarea"); + source.setAttribute("aria-label", t("rtSource")); operator.setAttribute("aria-label", t("rtOperator")); name.setAttribute("aria-label", t("rtName")); valuesInput.setAttribute("aria-label", t("rtValues")); + for (const [v, key] of RT_SOURCES) { const o = text("option", key); o.value = v; source.append(o); } + source.value = value.source || "header"; name.type = "text"; name.maxLength = 128; name.value = value.name || ""; valuesInput.rows = 1; valuesInput.spellcheck = false; valuesInput.maxLength = 8192; valuesInput.value = (value.values || []).join("\n"); + const negate = document.createElement("input"), ignore = document.createElement("input"); negate.type = ignore.type = "checkbox"; negate.className = ignore.className = "switch"; negate.checked = value.negate === true; ignore.checked = value.ignore_case === true; + const negateLabel = el("label", undefined, "check rt-flag"), ignoreLabel = el("label", undefined, "check rt-flag"); negateLabel.append(negate, text("span", "rtNegate")); ignoreLabel.append(ignore, text("span", "lbHashIgnoreCase")); + const remove = button("remove", () => { row.remove(); refresh(); onChange(); }); + const fillOperators = chosen => { operator.replaceChildren(...rtOperatorsFor(source.value).map(v => { const o = text("option", RT_OPERATORS.find(([x]) => x === v)[1]); o.value = v; return o; })); operator.value = rtOperatorsFor(source.value).includes(chosen) ? chosen : rtOperatorsFor(source.value)[0]; }; + const syncRow = () => { + const named = ["header", "cookie", "query"].includes(source.value); + // .check labels set their own display, so the hidden attribute is not enough. + name.hidden = !named; ignoreLabel.hidden = !named; ignoreLabel.style.display = named ? "" : "none"; valuesInput.hidden = operator.value === "exists"; + name.placeholder = { header: "X-Beta", cookie: "session", query: "tenant" }[source.value] || ""; + valuesInput.placeholder = { ip: "10.0.0.0/8\n2001:db8::/32", method: "POST\nPUT", country: "PL\nDE", host: "beta.example.com" }[source.value] || t("rtValuesPlaceholder"); + }; + fillOperators(value.operator || "equals"); syncRow(); + source.addEventListener("change", () => { fillOperators(operator.value); syncRow(); }); + operator.addEventListener("change", syncRow); + row.read = () => { + const result = { source: source.value, operator: operator.value }; + if (!name.hidden) result.name = name.value.trim(); + if (operator.value !== "exists") result.values = valuesInput.value.split("\n").map(v => v.trim()).filter(Boolean); + if (negate.checked) result.negate = true; + if (!ignoreLabel.hidden && ignore.checked) result.ignore_case = true; + return result; + }; + row.append(source, name, operator, valuesInput, negateLabel, ignoreLabel, remove); list.append(row); refresh(); + }; + const refresh = () => { empty.hidden = list.children.length > 0; }; + box.append(button("rtAddCondition", () => { add(); onChange(); })); + for (const value of values) add(value); refresh(); + return { read: () => [...list.children].map(row => row.read()), count: () => list.children.length }; +} + +// Routing tester for the Locations tab: works on the unsaved draft. +function routingTester(parent, readRoutes) { + const box = el("details", undefined, "vh-wide rt-tester"); box.append(text("summary", "rtTester")); parent.append(box); + const body = el("div", undefined, "rt-tester-body"); box.append(body); + const grid = el("div", undefined, "vh-grid"); body.append(grid); + const method = field(grid, "rt-method", "rtSourceMethod", "GET", "select", { values: ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].map(m => [m, m]) }); + const url = field(grid, "rt-url", "rtUrl", "/", "text", { maxLength: 4096 }); url.placeholder = "https://app.example.com/api/v2/items?tenant=acme"; + const ip = field(grid, "rt-ip", "rtSourceIp", "203.0.113.10", "text", { maxLength: 64 }); + const country = field(grid, "rt-country", "rtSourceCountry", "", "text", { maxLength: 2 }); country.placeholder = "PL"; + const headers = field(grid, "rt-headers", "rtHeaders", "", "textarea", { rows: 3, maxLength: 8192 }); headers.placeholder = "X-Beta: 1\nCookie: session=abc; staff=1\nUser-Agent: Mozilla/5.0"; + for (const control of [method, url, ip, country, headers]) control.removeAttribute("name"); + const out = el("div", undefined, "rt-result"); body.append(out); + const run = () => { + out.replaceChildren(); + let routes; try { routes = readRoutes(); } catch (cause) { out.append(el("p", cause.message, "fine rt-error")); return; } + const parsed = lbParseSample(url.value || "/"), hosts = lines(read("hosts")?.value || ""); + const request = { + method: method.value, path: parsed.path || "/", query: parsed.query, host: parsed.host || hosts.find(h => !h.startsWith("*")) || "", + client_ip: ip.value.trim(), country: country.value.trim().toUpperCase() || null, + headers: headers.value.split("\n").map(line => line.trim()).filter(line => line.includes(":")).map(line => [line.slice(0, line.indexOf(":")).trim(), line.slice(line.indexOf(":") + 1).trim()]) + }; + const { winner, trace } = rtEvaluate(routes, request); + const verdict = el("div", undefined, "rt-verdict"); + const routeName = winner ? winner.route.id : t("rtMainSource"); + verdict.append(text("span", "rtResult"), el("strong", routeName)); + const target = rtTarget(winner?.route || null, request); if (target) verdict.append(el("span", ` → ${target}`, "rt-target")); + if (winner?.conditional) verdict.append(text("span", "rtNotCached", "fine rt-badge")); + out.append(verdict); + const table = el("table", undefined, "lb-sim-table rt-trace"), head = el("tr"); + for (const key of ["locationId", "locationMatchType", "rtPathColumn", "rtConditionsColumn"]) head.append(text("th", key)); + table.append(head); + for (const item of trace) { + const tr = el("tr"); if (item === winner) tr.classList.add("is-winner"); + const mark = ok => el("span", ok ? "✓" : "✗", ok ? "rt-ok" : "rt-no"); + const conditionsCell = el("td"); + if (item.error) conditionsCell.append(el("span", `${t("rtBrowserRegex")}: ${item.error}`, "rt-no")); + else if (!item.conditional) conditionsCell.append(el("span", "—", "fine")); + else item.conditions.forEach((ok, i) => { const c = item.route.conditions[i]; conditionsCell.append(mark(ok), el("span", ` ${c.negate ? "!" : ""}${c.source}${c.name ? `(${c.name})` : ""} ${c.operator || "equals"} `, "rt-cond")); }); + const pathCell = el("td"); pathCell.append(mark(item.pathMatch)); if (item.route.enabled === false || item.route.internal) pathCell.append(el("span", ` ${t(item.route.internal ? "locationInternal" : "vhOff")}`, "fine")); + tr.append(el("td", item.route.id), el("td", t(`locationMatch_${item.type}`)), pathCell, conditionsCell); table.append(tr); + } + out.append(table, text("p", "rtTesterHelp", "fine")); + }; + // Backend for the chosen route: pinned backend, group or vhost pool + algorithm. + const rtTarget = (route, request) => { + if (route && (route.response || route.redirect)) return t(route.response ? "locationReturnShort" : "locationRedirectShort"); + if (route?.source?.type === "web_server") return `${t("locationWebServerShort")} ${route.source.web_service_id || ""}`; + if (route?.backend_id) return route.backend_id; + const members = balancingMembers(), explicit = Boolean(route?.backend_ids?.length); + const pool = lbEligible(explicit ? members.filter(m => route.backend_ids.includes(m.id)) : members, explicit); + if (!pool.length) return t("lbSimNoMembers"); + const own = route?.load_balancing, algorithm = own ? own.algorithm : str("algorithm"), hash = own ? own.hash || { source: "path" } : vhostBalancingControl?.hash() || {}; + const sticky = own ? own.sticky || "off" : str("sticky-mode"); + const label = t(LB_ALGORITHMS.find(([v]) => v === algorithm)?.[1] || "vhAlgorithm"); + let key = null; + if (sticky === "ip_hash" || algorithm === "ip_hash") key = request.client_ip; + else if (algorithm === "hash") { + const settings = hash, source = settings.source || "path"; + if (source === "header") key = rtHeaderValues(request, settings.name || "").join(",") || null; + else if (source === "cookie") key = rtConditionValues({ source: "cookie", name: settings.name }, request)[0] || null; + else if (source === "ip") key = request.client_ip; + else key = lbHashKey(settings, `https://${request.host || "host"}${request.path}${request.query !== null && request.query !== undefined ? `?${request.query}` : ""}`); + if (key && settings.ignore_case && !["ip", "host"].includes(source)) key = key.toLowerCase(); + } + if (key) return `${lbRank(str("id") || "vhost", key, pool)[0].id} (${label}, ${t("lbSimKey")}: ${key})`; + return `${pool.map(m => m.id).join(", ")} (${label})`; + }; + box.addEventListener("input", event => { event.stopPropagation(); run(); }); + box.addEventListener("change", event => event.stopPropagation()); + box.addEventListener("toggle", () => { if (box.open) run(); }); + return { run: () => { if (box.open) run(); } }; +} diff --git a/src/balance.rs b/src/balance.rs index 14daca5..0e2a159 100644 --- a/src/balance.rs +++ b/src/balance.rs @@ -7,3 +7,5 @@ include!("balance/pool_view.rs"); #[cfg(test)] include!("balance/tests.rs"); +#[cfg(test)] +include!("balance/hash_tests.rs"); diff --git a/src/balance/hash_tests.rs b/src/balance/hash_tests.rs new file mode 100644 index 0000000..528ab2b --- /dev/null +++ b/src/balance/hash_tests.rs @@ -0,0 +1,426 @@ +mod hash_tests { + use super::*; + + fn policy() -> crate::config::ValidationPolicy { + crate::config::ValidationPolicy { + proxy_addr: "127.0.0.1:8080".parse().unwrap(), + admin_addr: "127.0.0.1:9090".parse().unwrap(), + tls_addr: None, + cert_dir: None, + data_dir: None, + } + } + fn compile(value: serde_json::Value) -> anyhow::Result { + let cfg = serde_json::from_value(value)?; + crate::config::compile(cfg, 0, &policy()) + } + fn shards(load_balancing: serde_json::Value) -> Arc { + compile(serde_json::json!({ + "listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]}, + "vhosts":[{ + "id":"files","frontend":{"hosts":["files.localhost"],"listener_ids":["http"]}, + "backends":[ + {"id":"s1","url":"http://127.0.0.1:9001","allow_private":true}, + {"id":"s2","url":"http://127.0.0.1:9002","allow_private":true}, + {"id":"s3","url":"http://127.0.0.1:9003","allow_private":true}], + "load_balancing":load_balancing + }] + })) + .unwrap() + .pools[0] + .clone() + } + fn uri(value: &str) -> http::Uri { + value.parse().unwrap() + } + fn peer() -> IpAddr { + "192.0.2.10".parse().unwrap() + } + fn pick(pool: &Pool, path: &str, headers: &HeaderMap) -> String { + let selection = pool + .select_uri(peer(), headers, Some(&uri(path)), false) + .expect("selection"); + selection.lease.member.definition.id.clone() + } + + #[test] + fn hash_keys_follow_the_configured_source() { + let mut headers = HeaderMap::new(); + headers.insert("host", "Files.Example.com:8443".parse().unwrap()); + headers.insert("x-tenant", "Acme".parse().unwrap()); + headers.insert("cookie", "a=1; session=XYZ; b=2".parse().unwrap()); + let request = uri("/music/Album/track.MP3?user=42&x"); + let key = |value: serde_json::Value| { + let settings: HashSettings = serde_json::from_value(value).unwrap(); + settings.validate().unwrap(); + settings.key(peer(), &headers, Some(&request)) + }; + assert_eq!(key(serde_json::json!({})).as_deref(), Some("/music/Album/track.MP3")); + assert_eq!( + key(serde_json::json!({"ignore_case":true})).as_deref(), + Some("/music/album/track.mp3") + ); + assert_eq!(key(serde_json::json!({"path_depth":1})).as_deref(), Some("/music")); + assert_eq!(key(serde_json::json!({"path_depth":2})).as_deref(), Some("/music/Album")); + assert_eq!( + key(serde_json::json!({"path_depth":9})).as_deref(), + Some("/music/Album/track.MP3") + ); + assert_eq!( + key(serde_json::json!({"source":"uri"})).as_deref(), + Some("/music/Album/track.MP3?user=42&x") + ); + assert_eq!( + key(serde_json::json!({"source":"host"})).as_deref(), + Some("files.example.com") + ); + assert_eq!(key(serde_json::json!({"source":"ip"})).as_deref(), Some("192.0.2.10")); + assert_eq!( + key(serde_json::json!({"source":"header","name":"X-Tenant"})).as_deref(), + Some("Acme") + ); + assert_eq!( + key(serde_json::json!({"source":"cookie","name":"session"})).as_deref(), + Some("XYZ") + ); + assert_eq!( + key(serde_json::json!({"source":"query","name":"user"})).as_deref(), + Some("42") + ); + assert_eq!(key(serde_json::json!({"source":"query","name":"x"})), None); + assert_eq!(key(serde_json::json!({"source":"query","name":"missing"})), None); + assert_eq!(key(serde_json::json!({"source":"cookie","name":"missing"})), None); + assert_eq!(key(serde_json::json!({"source":"header","name":"x-missing"})), None); + // HTTP/2 requests carry the authority in the URI. + let settings: HashSettings = serde_json::from_value(serde_json::json!({"source":"host"})).unwrap(); + assert_eq!( + settings + .key(peer(), &HeaderMap::new(), Some(&uri("https://[2001:db8::1]:443/x"))) + .as_deref(), + Some("2001:db8::1") + ); + let mut v6 = HeaderMap::new(); + v6.insert("host", "[2001:db8::1]:8443".parse().unwrap()); + assert_eq!(settings.key(peer(), &v6, None).as_deref(), Some("2001:db8::1")); + } + + #[test] + fn hash_settings_are_validated() { + let invalid = [ + serde_json::json!({"source":"header"}), + serde_json::json!({"source":"header","name":"bad header"}), + serde_json::json!({"source":"cookie","name":"a;b"}), + serde_json::json!({"source":"path","name":"x"}), + serde_json::json!({"path_depth":33}), + serde_json::json!({"balance_factor":100}), + serde_json::json!({"balance_factor":1001}), + serde_json::json!({"fallback":"hash"}), + serde_json::json!({"fallback":"ip_hash"}), + ]; + for value in invalid { + let settings: HashSettings = serde_json::from_value(value.clone()).unwrap(); + assert!(settings.validate().is_err(), "{value} should be rejected"); + } + assert!(serde_json::from_value::(serde_json::json!({"unknown":1})).is_err()); + let ok: HashSettings = + serde_json::from_value(serde_json::json!({"balance_factor":125,"fallback":"random"})).unwrap(); + ok.validate().unwrap(); + } + + #[test] + fn default_settings_serialize_without_hash_block() { + let value = serde_json::to_value(Settings::default()).unwrap(); + assert!(value.get("hash").is_none()); + let mut settings = Settings::default(); + settings.algorithm = Algorithm::Hash; + settings.hash.source = HashSource::Cookie; + settings.hash.name = Some("sid".into()); + let value = serde_json::to_value(&settings).unwrap(); + assert_eq!(value["algorithm"], "hash"); + assert_eq!(value["hash"]["source"], "cookie"); + let back: Settings = serde_json::from_value(value).unwrap(); + assert_eq!(back.hash, settings.hash); + } + + #[test] + fn path_hash_is_stable_and_spreads_keys() { + let pool = shards(serde_json::json!({"algorithm":"hash","health_check":{"mode":"off"}})); + let mut counts = std::collections::HashMap::::new(); + for n in 0..3000 { + let path = format!("/media/{n}.mp3"); + let first = pick(&pool, &path, &HeaderMap::new()); + for _ in 0..3 { + assert_eq!(pick(&pool, &path, &HeaderMap::new()), first); + } + *counts.entry(first).or_default() += 1; + } + assert_eq!(counts.len(), 3); + for (member, count) in counts { + assert!((800..=1200).contains(&count), "{member} got {count} of 3000 keys"); + } + } + + #[test] + fn removing_a_member_only_moves_its_own_keys() { + let pool = shards(serde_json::json!({"algorithm":"hash","health_check":{"mode":"off"}})); + let paths: Vec = (0..600).map(|n| format!("/f/{n}")).collect(); + let before: Vec = paths.iter().map(|p| pick(&pool, p, &HeaderMap::new())).collect(); + let down = pool.members.iter().find(|m| m.definition.id == "s2").unwrap(); + down.state.set_healthy_for_test(false); + for (path, previous) in paths.iter().zip(&before) { + let now = pick(&pool, path, &HeaderMap::new()); + if previous == "s2" { + assert_ne!(now, "s2"); + } else { + assert_eq!(&now, previous, "{path} moved although its member stayed up"); + } + } + down.state.set_healthy_for_test(true); + for (path, previous) in paths.iter().zip(&before) { + assert_eq!(&pick(&pool, path, &HeaderMap::new()), previous); + } + } + + #[test] + fn weights_shift_the_share_of_keys() { + let pool = compile(serde_json::json!({ + "listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]}, + "vhosts":[{ + "id":"w","frontend":{"hosts":["w.localhost"],"listener_ids":["http"]}, + "backends":[ + {"id":"big","url":"http://127.0.0.1:9001","allow_private":true,"weight":3}, + {"id":"small","url":"http://127.0.0.1:9002","allow_private":true,"weight":1}], + "load_balancing":{"algorithm":"hash","health_check":{"mode":"off"}} + }] + })) + .unwrap() + .pools[0] + .clone(); + let big = (0..4000) + .filter(|n| pick(&pool, &format!("/k/{n}"), &HeaderMap::new()) == "big") + .count(); + assert!((2700..=3300).contains(&big), "weight 3:1 gave {big} of 4000"); + } + + #[test] + fn missing_key_uses_fallback_algorithm() { + let pool = shards(serde_json::json!({ + "algorithm":"hash","slow_start_seconds":0, + "hash":{"source":"cookie","name":"sid","fallback":"round_robin"}, + "health_check":{"mode":"off"} + })); + let mut seen = std::collections::HashSet::new(); + for _ in 0..6 { + seen.insert(pick(&pool, "/", &HeaderMap::new())); + } + assert_eq!(seen.len(), 3, "round robin fallback should visit every member"); + let mut headers = HeaderMap::new(); + headers.insert("cookie", "sid=user-7".parse().unwrap()); + let first = pick(&pool, "/", &headers); + for _ in 0..10 { + assert_eq!(pick(&pool, "/other", &headers), first); + } + assert_eq!(pool.preview(peer(), &headers, None).0.as_deref(), Some(first.as_str())); + assert!(!pool.hashes_request_uri()); + } + + #[test] + fn bounded_load_moves_overflow_to_the_next_member_for_the_key() { + let pool = shards(serde_json::json!({ + "algorithm":"hash","hash":{"balance_factor":125},"health_check":{"mode":"off"} + })); + let path = "/hot/object.mp3"; + let owner = pool.preview(peer(), &HeaderMap::new(), Some(&uri(path))).0.unwrap(); + let mut leases = Vec::new(); + // Keep the owner busy: with 125% and 3 members its cap is soon exceeded. + for _ in 0..4 { + let selection = pool.select_uri(peer(), &HeaderMap::new(), Some(&uri(path)), false).unwrap(); + leases.push(selection); + } + let owners: std::collections::HashSet<_> = leases + .iter() + .map(|s| s.lease.member.definition.id.clone()) + .collect(); + assert!(owners.contains(&owner)); + assert!(owners.len() > 1, "bounded load should spill a hot key: {owners:?}"); + drop(leases); + assert_eq!(pick(&pool, path, &HeaderMap::new()), owner); + } + + #[test] + fn random_two_choices_only_uses_eligible_members() { + let pool = shards(serde_json::json!({"algorithm":"random","slow_start_seconds":0,"health_check":{"mode":"off"}})); + pool.members[0].state.set_healthy_for_test(false); + let mut seen = std::collections::HashSet::new(); + for _ in 0..200 { + let selection = pool.select(peer(), &HeaderMap::new(), false).unwrap(); + seen.insert(selection.lease.member.definition.id.clone()); + } + assert!(!seen.contains("s1")); + assert_eq!(seen.len(), 2); + } + + #[test] + fn ip_hash_keeps_previous_member_mapping() { + // Same inputs and formula as before 0.40.2: pool id | client IP | member id. + let pool = shards(serde_json::json!({"algorithm":"ip_hash","health_check":{"mode":"off"}})); + let expected = pool + .members + .iter() + .min_by(|a, b| { + rendezvous_score("files", "192.0.2.10", &a.definition.id, 1) + .total_cmp(&rendezvous_score("files", "192.0.2.10", &b.definition.id, 1)) + }) + .unwrap() + .definition + .id + .clone(); + let selection = pool.select(peer(), &HeaderMap::new(), false).unwrap(); + assert_eq!(selection.lease.member.definition.id, expected); + } + + /// Reference values shared with `tools/dev/test_balance_simulator.js` (fixture `tests/fixtures/balance_rendezvous_vectors.txt`), which checks + /// that the panel simulator ranks members exactly like the proxy. + #[test] + fn rendezvous_reference_vectors() { + let order = |key: &str| { + let mut ids = vec![("s1", 1u16), ("s2", 1), ("s3", 2)]; + ids.sort_by(|a, b| { + rendezvous_score("files", key, a.0, a.1).total_cmp(&rendezvous_score("files", key, b.0, b.1)) + }); + ids.into_iter().map(|(id, _)| id).collect::>().join(",") + }; + let vectors: Vec<(String, String)> = ["/a.mp3", "/music/b.mp3", "/c", "tenant-42", "192.0.2.10"] + .iter() + .map(|key| (key.to_string(), order(key))) + .collect(); + let rendered = vectors + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join(";"); + let expected = include_str!("../../tests/fixtures/balance_rendezvous_vectors.txt").trim(); + assert_eq!(rendered, expected); + } + + #[test] + fn location_backend_group_balances_by_path_and_shares_member_state() { + let snapshot = compile(serde_json::json!({ + "listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]}, + "vhosts":[{ + "id":"site","frontend":{"hosts":["site.localhost"],"listener_ids":["http"]}, + "backends":[ + {"id":"app","url":"http://127.0.0.1:9000","allow_private":true}, + {"id":"mp3_1","url":"http://127.0.0.1:9011","allow_private":true,"pool_eligible":false}, + {"id":"mp3_2","url":"http://127.0.0.1:9012","allow_private":true,"pool_eligible":false}, + {"id":"mp3_3","url":"http://127.0.0.1:9013","allow_private":true,"pool_eligible":false}], + "load_balancing":{"algorithm":"least_connections","health_check":{"mode":"off"}, + "sticky":{"mode":"cookie"}}, + "routes":[{ + "id":"mp3","path_prefix":"\\.mp3$","match_type":"regex_insensitive", + "backend_ids":["mp3_1","mp3_2","mp3_3"], + "load_balancing":{"algorithm":"hash","hash":{"source":"path"}} + }] + }] + })) + .unwrap(); + let vhost_pool = snapshot.pools[0].clone(); + let route = snapshot.select("site.localhost", "/music/song.MP3").expect("mp3 route"); + let pool = route.pool.clone().unwrap(); + assert_eq!(pool.route.as_deref(), Some("mp3")); + assert_eq!(pool.members.len(), 3); + assert!(!pool.cookie_affinity(), "location balancing replaces vhost affinity"); + assert!(pool.hashes_request_uri()); + for member in &pool.members { + let shared = vhost_pool + .members + .iter() + .find(|m| m.definition.id == member.definition.id) + .unwrap(); + assert!(Arc::ptr_eq(&member.state, &shared.state)); + } + let mut owners = std::collections::HashSet::new(); + for n in 0..60 { + let path = format!("/music/{n}.mp3"); + let a = pick(&pool, &path, &HeaderMap::new()); + assert_eq!(pick(&pool, &path, &HeaderMap::new()), a); + assert!(a.starts_with("mp3_")); + owners.insert(a); + } + assert_eq!(owners.len(), 3); + // The vhost pool itself never uses location-only backends. + for _ in 0..10 { + let selection = vhost_pool.select(peer(), &HeaderMap::new(), false).unwrap(); + assert_eq!(selection.lease.member.definition.id, "app"); + } + // Main pages still go to the vhost pool. + let main = snapshot.select("site.localhost", "/index.html").unwrap(); + assert!(Arc::ptr_eq(main.pool.as_ref().unwrap(), &vhost_pool)); + // Affinity cookies of the vhost pool are not forwarded by the location pool. + let mut headers = HeaderMap::new(); + headers.insert("cookie", "RP_AFFINITY_site=abc; keep=1".parse().unwrap()); + pool.strip_affinity(&mut headers); + assert_eq!(headers.get("cookie").unwrap(), "keep=1"); + } + + #[test] + fn location_group_without_override_inherits_vhost_balancing() { + let snapshot = compile(serde_json::json!({ + "listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]}, + "vhosts":[{ + "id":"site","frontend":{"hosts":["site.localhost"],"listener_ids":["http"]}, + "backends":[ + {"id":"a","url":"http://127.0.0.1:9001","allow_private":true}, + {"id":"b","url":"http://127.0.0.1:9002","allow_private":true}, + {"id":"c","url":"http://127.0.0.1:9003","allow_private":true}], + "load_balancing":{"algorithm":"round_robin","slow_start_seconds":0,"health_check":{"mode":"off"}, + "sticky":{"mode":"cookie"}}, + "routes":[{"id":"api","path_prefix":"/api","backend_ids":["b","c"]}] + }] + })) + .unwrap(); + let pool = snapshot.select("site.localhost", "/api/x").unwrap().pool.clone().unwrap(); + assert_eq!(pool.settings.algorithm, Algorithm::RoundRobin); + assert!(pool.cookie_affinity()); + let selection = pool.select(peer(), &HeaderMap::new(), false).unwrap(); + let cookie = selection.cookie.unwrap(); + assert!(cookie.to_str().unwrap().starts_with("RP_AFFINITY_site__api=")); + // The vhost pool strips location affinity cookies before the origin. + let mut headers = HeaderMap::new(); + headers.insert("cookie", "RP_AFFINITY_site__api=x; app=1".parse().unwrap()); + snapshot.pools[0].strip_affinity(&mut headers); + assert_eq!(headers.get("cookie").unwrap(), "app=1"); + } + + #[test] + fn invalid_location_groups_are_rejected() { + let base = |route: serde_json::Value| { + serde_json::json!({ + "listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]}, + "vhosts":[{ + "id":"site","frontend":{"hosts":["site.localhost"],"listener_ids":["http"]}, + "backends":[ + {"id":"a","url":"http://127.0.0.1:9001","allow_private":true}, + {"id":"b","url":"http://127.0.0.1:9002","allow_private":true}], + "load_balancing":{"health_check":{"mode":"off"}}, + "routes":[route] + }] + }) + }; + for route in [ + serde_json::json!({"id":"x","path_prefix":"/x","backend_ids":["missing"]}), + serde_json::json!({"id":"x","path_prefix":"/x","backend_ids":["a","a"]}), + serde_json::json!({"id":"x","path_prefix":"/x","backend_id":"a","backend_ids":["b"]}), + serde_json::json!({"id":"x","path_prefix":"/x","backend_id":"a","load_balancing":{"algorithm":"hash"}}), + serde_json::json!({"id":"x","path_prefix":"/x","load_balancing":{"algorithm":"hash","hash":{"source":"header"}}}), + serde_json::json!({"id":"x","path_prefix":"/x","load_balancing":{"algorithm":"hash","hash":{"balance_factor":50}}}), + ] { + assert!(compile(base(route.clone())).is_err(), "{route} should be rejected"); + } + assert!(compile(base(serde_json::json!({ + "id":"x","path_prefix":"/x","backend_ids":["a","b"], + "load_balancing":{"algorithm":"hash","hash":{"source":"query","name":"id","fallback":"least_connections"}} + }))) + .is_ok()); + } +} diff --git a/src/balance/health.rs b/src/balance/health.rs index d72c199..0d8613b 100644 --- a/src/balance/health.rs +++ b/src/balance/health.rs @@ -464,6 +464,14 @@ pub struct Pool { cookie_name: String, cursor: AtomicU64, scheduling: Mutex>, + /// Location backend group: members were chosen explicitly, so `pool_eligible` + /// (which only controls membership of the vhost-wide pool) is ignored. + explicit_members: bool, + /// Location id for a pool derived from the vhost pool. + pub route: Option, + /// Shared by a vhost pool and its location pools: set when any of them issues an + /// affinity cookie, so every one of them strips those cookies. + affinity_cookies: Arc, } #[derive(Debug)] pub struct Lease { diff --git a/src/balance/model.rs b/src/balance/model.rs index 0f484ad..ae534dc 100644 --- a/src/balance/model.rs +++ b/src/balance/model.rs @@ -29,6 +29,257 @@ pub enum Algorithm { LeastTraffic, Adaptive, IpHash, + /// Consistent (rendezvous) hash of a request attribute selected by [`HashSettings`]. + Hash, + /// Power of two random choices: two random members, the less loaded one wins. + Random, +} +impl Algorithm { + /// Algorithms usable when a hash key is missing from a request. + pub fn valid_hash_fallback(self) -> bool { + matches!( + self, + Self::RoundRobin | Self::LeastConnections | Self::LeastTraffic | Self::Adaptive | Self::Random + ) + } +} +/// Request attribute used as the key of the `hash` algorithm. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HashSource { + /// Request path without the query string (HAProxy `balance hash path` / `balance uri`). + #[default] + Path, + /// Path and query string (HAProxy `balance uri whole`). + Uri, + /// Request host name without the port. + Host, + /// Client address as seen by RustProxy (same input as `ip_hash`). + Ip, + /// Value of one request header (`name`). + Header, + /// Value of one request cookie (`name`). + Cookie, + /// Value of one query string parameter (`name`). + Query, +} +impl HashSource { + pub fn needs_name(self) -> bool { + matches!(self, Self::Header | Self::Cookie | Self::Query) + } +} +fn default_hash_fallback() -> Algorithm { + Algorithm::RoundRobin +} +/// Settings of the `hash` algorithm. Hashing is always consistent: members are ranked +/// with weighted rendezvous hashing, so adding, removing or ejecting a member only moves +/// the keys that belong to that member. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct HashSettings { + pub source: HashSource, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Number of leading path directories to hash; 0 hashes the whole path. + pub path_depth: u8, + pub ignore_case: bool, + /// Consistent hashing with bounded loads (percent of the average load per member); + /// 0 disables the bound, otherwise 101..=1000. + pub balance_factor: u16, + /// Algorithm used when the request has no value for the key. + #[serde(default = "default_hash_fallback")] + pub fallback: Algorithm, +} +impl Default for HashSettings { + fn default() -> Self { + Self { + source: HashSource::Path, + name: None, + path_depth: 0, + ignore_case: false, + balance_factor: 0, + fallback: default_hash_fallback(), + } + } +} +impl HashSettings { + pub fn is_default(&self) -> bool { + self == &Self::default() + } + pub fn validate(&self) -> Result<()> { + if self.source.needs_name() { + let name = self.name.as_deref().unwrap_or(""); + ensure!( + !name.is_empty() && name.len() <= 128, + "hash key name is required for header, cookie and query keys (1..128 characters)" + ); + if self.source == HashSource::Header { + ensure!( + http::HeaderName::from_bytes(name.as_bytes()).is_ok(), + "hash header name is not a valid HTTP header name" + ); + } else { + ensure!( + name.bytes() + .all(|b| b.is_ascii_graphic() && !matches!(b, b';' | b'=' | b'&' | b',')), + "hash cookie/query name must be printable ASCII without ; = & or ," + ); + } + } else { + ensure!( + self.name.as_deref().is_none_or(str::is_empty), + "hash key name is only used with header, cookie and query keys" + ); + } + ensure!(self.path_depth <= 32, "hash path_depth must be 0..32"); + ensure!( + self.balance_factor == 0 || (101..=1000).contains(&self.balance_factor), + "hash balance_factor must be 0 (off) or 101..1000" + ); + ensure!( + self.fallback.valid_hash_fallback(), + "hash fallback must be round_robin, least_connections, least_traffic, adaptive or random" + ); + Ok(()) + } + /// Extracts the hash key for a request; `None` when the request has no value. + pub fn key(&self, peer: IpAddr, headers: &HeaderMap, uri: Option<&http::Uri>) -> Option { + let raw: String = match self.source { + HashSource::Ip => return Some(crate::vhost::canonical_ip(peer).to_string()), + HashSource::Path => { + let path = uri.map(http::Uri::path).filter(|p| !p.is_empty())?; + limit_path_depth(path, self.path_depth).to_owned() + } + HashSource::Uri => { + let uri = uri?; + let path = limit_path_depth(uri.path(), self.path_depth); + match uri.query() { + Some(query) => format!("{path}?{query}"), + None => path.to_owned(), + } + } + HashSource::Host => { + let host = uri + .and_then(http::Uri::host) + .map(|h| h.trim_start_matches('[').trim_end_matches(']').to_owned()) + .or_else(|| { + headers + .get(http::header::HOST) + .and_then(|v| v.to_str().ok()) + .map(|v| strip_port(v).to_owned()) + })?; + let host = host.trim_end_matches('.').to_ascii_lowercase(); + if host.is_empty() { + return None; + } + return Some(host); + } + HashSource::Header => { + let name = self.name.as_deref()?; + let values: Vec<&str> = headers + .get_all(name) + .iter() + .filter_map(|v| v.to_str().ok()) + .map(str::trim) + .collect(); + let joined = values.join(","); + if joined.is_empty() { + return None; + } + joined + } + HashSource::Cookie => { + let name = self.name.as_deref()?; + headers + .get_all(http::header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .filter_map(|pair| pair.trim().split_once('=')) + .find(|(n, _)| *n == name) + .map(|(_, v)| v.trim().to_owned()) + .filter(|v| !v.is_empty())? + } + HashSource::Query => { + let name = self.name.as_deref()?; + uri?.query()? + .split('&') + .map(|pair| pair.split_once('=').unwrap_or((pair, ""))) + .find(|(n, _)| *n == name) + .map(|(_, v)| v.to_owned()) + .filter(|v| !v.is_empty())? + } + }; + Some(if self.ignore_case { + raw.to_lowercase() + } else { + raw + }) + } +} +fn strip_port(host: &str) -> &str { + if let Some(rest) = host.strip_prefix('[') { + return rest.split_once(']').map_or(host, |(inner, _)| inner); + } + match host.rsplit_once(':') { + Some((name, port)) if !name.contains(':') && port.bytes().all(|b| b.is_ascii_digit()) => name, + _ => host, + } +} +/// Keeps the first `depth` directories of a path (`/a/b/c.mp3`, depth 2 → `/a/b`). +fn limit_path_depth(path: &str, depth: u8) -> &str { + if depth == 0 { + return path; + } + let mut seen = 0u8; + for (index, byte) in path.bytes().enumerate() { + if byte == b'/' && index > 0 { + seen += 1; + if seen == depth { + return &path[..index]; + } + } + } + path +} +/// Rendezvous score of one member for a key; the lowest score wins. +pub(crate) fn rendezvous_score(pool_id: &str, key: &str, member_id: &str, weight: u16) -> f64 { + let mut hash = Sha256::new(); + hash.update(pool_id.as_bytes()); + hash.update(b"|"); + hash.update(key.as_bytes()); + hash.update(b"|"); + hash.update(member_id.as_bytes()); + let digest = hash.finalize(); + let n = u64::from_be_bytes([ + digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], + ]); + let unit = (n as f64 + 1.0) / (u64::MAX as f64 + 2.0); + -unit.max(f64::MIN_POSITIVE).ln() / f64::from(weight.max(1)) +} +/// Per-location balancing override: the location uses its own algorithm over its +/// backend group while sharing health state with the vhost pool. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct RouteBalancing { + pub algorithm: Algorithm, + #[serde(skip_serializing_if = "HashSettings::is_default")] + pub hash: HashSettings, + pub sticky: StickyMode, +} +impl Default for RouteBalancing { + fn default() -> Self { + Self { + algorithm: Algorithm::Hash, + hash: HashSettings::default(), + sticky: StickyMode::Off, + } + } +} +impl RouteBalancing { + pub fn validate(&self) -> Result<()> { + self.hash.validate() + } } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -197,6 +448,8 @@ pub struct Settings { pub retry: RetryPolicy, pub sticky: Sticky, pub slow_start_seconds: u64, + #[serde(skip_serializing_if = "HashSettings::is_default")] + pub hash: HashSettings, } impl Default for Settings { fn default() -> Self { @@ -208,6 +461,7 @@ impl Default for Settings { retry: RetryPolicy::default(), sticky: Sticky::default(), slow_start_seconds: 10, + hash: HashSettings::default(), } } } @@ -233,6 +487,7 @@ impl Settings { passive } pub fn validate(&self) -> Result<()> { + self.hash.validate()?; let h = &self.health_check; let k = &self.keepalive; ensure!( diff --git a/src/balance/pool_core.rs b/src/balance/pool_core.rs index 66e122b..d278774 100644 --- a/src/balance/pool_core.rs +++ b/src/balance/pool_core.rs @@ -10,6 +10,7 @@ impl Pool { "invalid compiled pool" ); let fingerprint = Sha256::digest(serde_json::to_vec(&(definitions, &settings))?).to_vec(); + let settings_cookie = settings.sticky.mode == StickyMode::Cookie; let cookie_name = settings .sticky .cookie_name @@ -45,8 +46,85 @@ impl Pool { cookie_name, cursor: AtomicU64::new(0), scheduling: Mutex::new(std::collections::HashMap::new()), + explicit_members: false, + route: None, + affinity_cookies: Arc::new(AtomicBool::new(settings_cookie)), }) } + /// Builds the pool of one location from this (vhost) pool. Members are shared, so + /// health checks, passive ejection, concurrency limits and statistics stay common; + /// only the selection (members, algorithm, hash key, affinity) is location-specific. + /// `member_ids` empty means every member of the vhost pool. + pub fn derive( + &self, + route_id: &str, + member_ids: &[String], + balancing: Option<&RouteBalancing>, + ) -> Result { + let members: Vec> = if member_ids.is_empty() { + self.members.clone() + } else { + member_ids + .iter() + .map(|id| { + self.members + .iter() + .find(|m| &m.definition.id == id) + .cloned() + .ok_or_else(|| anyhow::anyhow!("location {route_id} references unknown backend {id}")) + }) + .collect::>()? + }; + ensure!(!members.is_empty(), "location {route_id} has an empty backend group"); + let mut settings = self.settings.clone(); + if let Some(balancing) = balancing { + balancing.validate()?; + settings.algorithm = balancing.algorithm; + settings.hash = balancing.hash.clone(); + settings.sticky.mode = balancing.sticky; + } + if settings.sticky.mode == StickyMode::Cookie { + self.affinity_cookies.store(true, Ordering::Relaxed); + } + let fingerprint = Sha256::digest(serde_json::to_vec(&( + &self.fingerprint, + route_id, + member_ids, + balancing, + ))?) + .to_vec(); + Ok(Self { + id: self.id.clone(), + settings, + members, + fingerprint, + cookie_name: format!("{}__{}", self.cookie_name, route_id), + cursor: AtomicU64::new(0), + scheduling: Mutex::new(std::collections::HashMap::new()), + explicit_members: !member_ids.is_empty(), + route: Some(route_id.to_owned()), + affinity_cookies: self.affinity_cookies.clone(), + }) + } + fn affinity_cookie_name(&self, name: &str) -> bool { + // A location pool strips the vhost cookie too, and the vhost pool strips the + // cookies of its locations (`__`), so affinity tokens + // never reach an origin. + let base = self + .route + .as_ref() + .and_then(|route| self.cookie_name.strip_suffix(&format!("__{route}"))) + .unwrap_or(&self.cookie_name); + name == self.cookie_name + || name == base + || name.strip_prefix(base).is_some_and(|rest| rest.starts_with("__")) + } + fn member_selectable(&self, m: &Member) -> bool { + (self.explicit_members || m.definition.pool_eligible) + && m.definition.enabled + && !m.definition.drain + && m.state.healthy() + } pub fn reuse_observations(&mut self, previous: &Pool) { for member in &mut self.members { let Some(old) = previous @@ -92,10 +170,7 @@ impl Pool { .members .iter() .filter(|m| { - m.definition.pool_eligible - && m.definition.enabled - && !m.definition.drain - && m.state.healthy() + self.member_selectable(m) && m.state.has_capacity(m.definition.max_concurrent_requests) && !excluded.iter().any(|id| id == &m.definition.id) }) @@ -108,6 +183,15 @@ impl Pool { pub fn ready(&self) -> bool { !self.eligible_healthy_excluding(&[]).is_empty() } + /// True when selection reads the request URI (path, URI, host or query hashing). + pub fn hashes_request_uri(&self) -> bool { + self.settings.algorithm == Algorithm::Hash + && self.settings.sticky.mode != StickyMode::IpHash + && matches!( + self.settings.hash.source, + HashSource::Path | HashSource::Uri | HashSource::Host | HashSource::Query + ) + } pub fn cookie_affinity(&self) -> bool { self.settings.sticky.mode == StickyMode::Cookie } @@ -128,7 +212,7 @@ impl Pool { } } pub fn strip_affinity_response(&self, headers: &mut HeaderMap) { - if !self.cookie_affinity() { + if !self.cookie_affinity() && !self.affinity_cookies.load(Ordering::Relaxed) { return; } let retained: Vec<_> = headers @@ -139,7 +223,7 @@ impl Pool { .to_str() .ok() .and_then(|v| v.split_once('=')) - .is_none_or(|(name, _)| name.trim() != self.cookie_name) + .is_none_or(|(name, _)| !self.affinity_cookie_name(name.trim())) }) .cloned() .collect(); @@ -149,7 +233,7 @@ impl Pool { } } pub fn strip_affinity(&self, headers: &mut HeaderMap) { - if !self.cookie_affinity() { + if !self.cookie_affinity() && !self.affinity_cookies.load(Ordering::Relaxed) { return; } let values: Vec = headers @@ -164,7 +248,7 @@ impl Pool { .filter(|part| { part.trim() .split_once('=') - .is_none_or(|(n, _)| n != self.cookie_name) + .is_none_or(|(n, _)| !self.affinity_cookie_name(n)) }) .map(str::trim) .collect::>() @@ -208,15 +292,13 @@ impl Pool { &self, peer: IpAddr, headers: &HeaderMap, + uri: Option<&http::Uri>, tls: bool, excluded: &[String], ) -> Option { if self.members.len() == 1 && !self.cookie_affinity() { let member = &self.members[0]; - if !member.definition.pool_eligible - || !member.definition.enabled - || member.definition.drain - || !member.state.healthy() + if !self.member_selectable(member) || excluded.iter().any(|id| id == &member.definition.id) || !member .state @@ -243,7 +325,7 @@ impl Pool { let matched = existing.and_then(|token| { self.members.iter().find(|m| { m.token == token - && m.definition.pool_eligible + && (self.explicit_members || m.definition.pool_eligible) && m.definition.enabled && m.state.healthy() && m.state.has_capacity(m.definition.max_concurrent_requests) @@ -253,94 +335,9 @@ impl Pool { if members.is_empty() && matched.is_none() { return None; } - let cursor = self.cursor.fetch_add(1, Ordering::Relaxed); - let selected = if let Some(member) = matched { - member - } else { - if self.settings.algorithm == Algorithm::RoundRobin - && self.settings.sticky.mode != StickyMode::IpHash - { - let mut scheduling = lock(&self.scheduling); - let mut chosen = members[0]; - let mut best = f64::NEG_INFINITY; - let mut total = 0.0; - for member in &members { - let weight = member - .state - .weight(member.definition.weight, self.settings.slow_start_seconds); - let current = - if let Some(current) = scheduling.get_mut(member.definition.id.as_str()) { - current - } else { - scheduling - .entry(member.definition.id.clone()) - .or_insert(0.0) - }; - *current += weight; - total += weight; - if *current > best { - best = *current; - chosen = *member; - } - } - if let Some(current) = scheduling.get_mut(&chosen.definition.id) { - *current -= total; - } - chosen - } else { - let mut chosen = members[(cursor as usize) % members.len()]; - let mut best = f64::INFINITY; - let algorithm = if self.settings.sticky.mode == StickyMode::IpHash { - Algorithm::IpHash - } else { - self.settings.algorithm - }; - let hash_ip = (algorithm == Algorithm::IpHash) - .then(|| crate::vhost::canonical_ip(peer).to_string()); - for offset in 0..members.len() { - let index = ((cursor as usize) % members.len() + offset) % members.len(); - let member = members[index]; - let active = member.state.active.load(Ordering::Relaxed) as f64; - let score = match algorithm { - Algorithm::IpHash => { - let mut hash = Sha256::new(); - hash.update(self.id.as_bytes()); - hash.update(b"|"); - hash.update(hash_ip.as_deref().expect("hash address").as_bytes()); - hash.update(b"|"); - hash.update(member.definition.id.as_bytes()); - let digest = hash.finalize(); - let n = u64::from_be_bytes([ - digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], - digest[6], digest[7], - ]); - let unit = (n as f64 + 1.0) / (u64::MAX as f64 + 2.0); - -unit.max(f64::MIN_POSITIVE).ln() / member.definition.weight as f64 - } - _ => { - let weight = member - .state - .weight(member.definition.weight, self.settings.slow_start_seconds); - match algorithm { - Algorithm::LeastTraffic => { - (member.state.traffic_rate() + (active + 1.0) * 1024.0) / weight - } - Algorithm::Adaptive => { - ((active + 1.0) * member.state.latency() - + member.state.traffic_rate() / 16_384.0) - / weight - } - _ => (active + 1.0) / weight, - } - } - }; - if score < best { - best = score; - chosen = member; - } - } - chosen - } + let selected = match matched { + Some(member) => member, + None => self.choose(&members, peer, headers, uri)?, }; if !selected .state @@ -371,4 +368,187 @@ impl Pool { cookie, }) } + /// Effective algorithm and hash key for a request. `ip_hash` affinity overrides the + /// algorithm; a `hash` request without a key value uses the configured fallback. + fn plan( + &self, + peer: IpAddr, + headers: &HeaderMap, + uri: Option<&http::Uri>, + ) -> (Algorithm, Option) { + let algorithm = if self.settings.sticky.mode == StickyMode::IpHash { + Algorithm::IpHash + } else { + self.settings.algorithm + }; + match algorithm { + Algorithm::IpHash => ( + Algorithm::IpHash, + Some(crate::vhost::canonical_ip(peer).to_string()), + ), + Algorithm::Hash => match self.settings.hash.key(peer, headers, uri) { + Some(key) => (Algorithm::Hash, Some(key)), + None => (self.settings.hash.fallback, None), + }, + other => (other, None), + } + } + /// Members ordered by rendezvous score for `key` (best first). + fn rendezvous_order<'a>(&self, members: &[&'a Arc], key: &str) -> Vec<&'a Arc> { + let mut ranked: Vec<(f64, &Arc)> = members + .iter() + .map(|m| { + ( + rendezvous_score(&self.id, key, &m.definition.id, m.definition.weight), + *m, + ) + }) + .collect(); + ranked.sort_by(|a, b| a.0.total_cmp(&b.0)); + ranked.into_iter().map(|(_, m)| m).collect() + } + fn choose<'a>( + &self, + members: &[&'a Arc], + peer: IpAddr, + headers: &HeaderMap, + uri: Option<&http::Uri>, + ) -> Option<&'a Arc> { + let (algorithm, key) = self.plan(peer, headers, uri); + let cursor = self.cursor.fetch_add(1, Ordering::Relaxed); + match algorithm { + Algorithm::IpHash => { + let ordered = self.rendezvous_order(members, key.as_deref()?); + ordered.first().copied() + } + Algorithm::Hash => { + let ordered = self.rendezvous_order(members, key.as_deref()?); + let factor = self.settings.hash.balance_factor; + if factor == 0 || ordered.len() < 2 { + return ordered.first().copied(); + } + // Consistent hashing with bounded loads: a member may take a new request + // only while its in-flight count stays within `factor`% of its weighted + // share of the pool load; otherwise the next member in the key's + // rendezvous order is used, so overflow stays deterministic per key. + let total_active: u64 = members + .iter() + .map(|m| m.state.active.load(Ordering::Relaxed)) + .sum(); + let total_weight: f64 = members + .iter() + .map(|m| f64::from(m.definition.weight.max(1))) + .sum(); + let load = (total_active + 1) as f64 * f64::from(factor) / 100.0; + ordered + .iter() + .copied() + .find(|m| { + let share = f64::from(m.definition.weight.max(1)) / total_weight; + let cap = (load * share).ceil().max(1.0); + (m.state.active.load(Ordering::Relaxed) + 1) as f64 <= cap + }) + .or_else(|| ordered.first().copied()) + } + Algorithm::RoundRobin => Some(self.smooth_round_robin(members)), + Algorithm::Random => { + let len = members.len(); + if len == 1 { + return Some(members[0]); + } + let mut rng = rand::rng(); + let first = rng.random_range(0..len); + let mut second = rng.random_range(0..len - 1); + if second >= first { + second += 1; + } + let score = |m: &Arc| { + let weight = m + .state + .weight(m.definition.weight, self.settings.slow_start_seconds); + (m.state.active.load(Ordering::Relaxed) as f64 + 1.0) / weight + }; + let (a, b) = (members[first], members[second]); + Some(if score(b) < score(a) { b } else { a }) + } + Algorithm::LeastConnections | Algorithm::LeastTraffic | Algorithm::Adaptive => { + let mut chosen = members[(cursor as usize) % members.len()]; + let mut best = f64::INFINITY; + for offset in 0..members.len() { + let index = ((cursor as usize) % members.len() + offset) % members.len(); + let member = members[index]; + let active = member.state.active.load(Ordering::Relaxed) as f64; + let weight = member + .state + .weight(member.definition.weight, self.settings.slow_start_seconds); + let score = match algorithm { + Algorithm::LeastTraffic => { + (member.state.traffic_rate() + (active + 1.0) * 1024.0) / weight + } + Algorithm::Adaptive => { + ((active + 1.0) * member.state.latency() + + member.state.traffic_rate() / 16_384.0) + / weight + } + _ => (active + 1.0) / weight, + }; + if score < best { + best = score; + chosen = member; + } + } + Some(chosen) + } + } + } + fn smooth_round_robin<'a>(&self, members: &[&'a Arc]) -> &'a Arc { + let mut scheduling = lock(&self.scheduling); + let mut chosen = members[0]; + let mut best = f64::NEG_INFINITY; + let mut total = 0.0; + for member in members { + let weight = member + .state + .weight(member.definition.weight, self.settings.slow_start_seconds); + let current = if let Some(current) = scheduling.get_mut(member.definition.id.as_str()) { + current + } else { + scheduling + .entry(member.definition.id.clone()) + .or_insert(0.0) + }; + *current += weight; + total += weight; + if *current > best { + best = *current; + chosen = *member; + } + } + if let Some(current) = scheduling.get_mut(&chosen.definition.id) { + *current -= total; + } + chosen + } + /// Which member would serve a request right now, without taking a lease. Used by + /// the panel and diagnostics; returns the member id and the hash key (if any). + pub fn preview( + &self, + peer: IpAddr, + headers: &HeaderMap, + uri: Option<&http::Uri>, + ) -> (Option, Option) { + let members = self.candidates_excluding(&[]); + if members.is_empty() { + return (None, None); + } + let (algorithm, key) = self.plan(peer, headers, uri); + let member = match (&algorithm, &key) { + (Algorithm::Hash | Algorithm::IpHash, Some(key)) => self + .rendezvous_order(&members, key) + .first() + .map(|m| m.definition.id.clone()), + _ => None, + }; + (member, key) + } } diff --git a/src/balance/pool_selection.rs b/src/balance/pool_selection.rs index a7284f3..a6a6e50 100644 --- a/src/balance/pool_selection.rs +++ b/src/balance/pool_selection.rs @@ -1,6 +1,15 @@ impl Pool { pub fn select(&self, peer: IpAddr, headers: &HeaderMap, tls: bool) -> Option { - self.select_excluding(peer, headers, tls, &[]) + self.select_excluding(peer, headers, None, tls, &[]) + } + pub fn select_uri( + &self, + peer: IpAddr, + headers: &HeaderMap, + uri: Option<&http::Uri>, + tls: bool, + ) -> Option { + self.select_excluding(peer, headers, uri, tls, &[]) } pub fn select_retry( &self, @@ -9,17 +18,14 @@ impl Pool { tls: bool, excluded: &[String], ) -> Option { - self.select_excluding(peer, headers, tls, excluded) + self.select_excluding(peer, headers, None, tls, excluded) } fn eligible_healthy_excluding(&self, excluded: &[String]) -> Vec<&Arc> { let all: Vec<_> = self .members .iter() .filter(|m| { - m.definition.pool_eligible - && m.definition.enabled - && !m.definition.drain - && m.state.healthy() + self.member_selectable(m) && !excluded.iter().any(|id| id == &m.definition.id) }) .collect(); @@ -65,7 +71,17 @@ impl Pool { headers: &HeaderMap, tls: bool, ) -> Result { - self.select_retry_wait(peer, headers, tls, &[]).await + self.select_retry_wait_uri(peer, headers, None, tls, &[]).await + } + /// Like [`Pool::select_wait`], with the request URI for path/URI/host/query hashing. + pub async fn select_wait_uri( + &self, + peer: IpAddr, + headers: &HeaderMap, + uri: Option<&http::Uri>, + tls: bool, + ) -> Result { + self.select_retry_wait_uri(peer, headers, uri, tls, &[]).await } pub async fn select_member_wait(&self, id: &str) -> Result { let Some(member) = self.members.iter().find(|m| { @@ -108,7 +124,18 @@ impl Pool { tls: bool, excluded: &[String], ) -> Result { - if let Some(selection) = self.select_retry(peer, headers, tls, excluded) { + self.select_retry_wait_uri(peer, headers, None, tls, excluded) + .await + } + pub async fn select_retry_wait_uri( + &self, + peer: IpAddr, + headers: &HeaderMap, + uri: Option<&http::Uri>, + tls: bool, + excluded: &[String], + ) -> Result { + if let Some(selection) = self.select_excluding(peer, headers, uri, tls, excluded) { return Ok(selection); } let Some(wait_ms) = self.capacity_wait_ms(excluded) else { @@ -119,7 +146,7 @@ impl Pool { if self.eligible_healthy_excluding(excluded).is_empty() { return Err(SelectionFailure::Unavailable); } - if let Some(selection) = self.select_retry(peer, headers, tls, excluded) { + if let Some(selection) = self.select_excluding(peer, headers, uri, tls, excluded) { return Ok(selection); } if wait_ms == 0 || started.elapsed() >= Duration::from_millis(wait_ms) { diff --git a/src/config.rs b/src/config.rs index fe9125d..e7ea08c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -12,3 +12,5 @@ include!("config/tests.rs"); include!("config/route_policy_tests.rs"); #[cfg(test)] include!("config/transport_tests.rs"); +#[cfg(test)] +include!("config/routing_conditions_tests.rs"); diff --git a/src/config/model.rs b/src/config/model.rs index 147aba0..02f942f 100644 --- a/src/config/model.rs +++ b/src/config/model.rs @@ -244,6 +244,8 @@ pub struct CompiledLocationRedirect { #[derive(Debug, Clone)] pub struct CompiledRoute { + /// Request conditions besides the path (all must hold); `None` for plain locations. + pub conditions: Option>, pub backend_id: Option, pub bindings: Vec, pub frontend: Option>, @@ -272,6 +274,11 @@ pub struct CompiledRoute { } #[derive(Debug)] pub struct CompiledFrontend { + /// Some enabled location has request conditions: the route is selected again + /// with the final client address (and country) before forwarding. + pub conditional_routes: bool, + /// Some location condition tests the client country. + pub route_conditions_country: bool, pub websockets: bool, pub websocket_legacy_support: bool, pub websocket_rfc8441: bool, diff --git a/src/config/routing.rs b/src/config/routing.rs index b7553b4..bfdd480 100644 --- a/src/config/routing.rs +++ b/src/config/routing.rs @@ -235,6 +235,17 @@ fn compile_routing( .map(|entry| (entry.acl.clone(), entry.countries.clone())) .unwrap_or_else(|| (None, crate::rate_limit::CountryAccess::default())); let frontend = Arc::new(CompiledFrontend { + conditional_routes: host + .routes + .iter() + .any(|route| route.enabled && !route.conditions.is_empty()), + route_conditions_country: host.routes.iter().any(|route| { + route.enabled + && route + .conditions + .iter() + .any(|c| c.source == crate::vhost::ConditionSource::Country) + }), metrics, websockets: host.websockets, websocket_legacy_support: host.websocket_legacy_support, @@ -315,6 +326,7 @@ fn compile_routing( ), }; let fallback = Arc::new(CompiledRoute { + conditions: None, backend_id: None, bindings: frontend.bindings.clone(), frontend: Some(frontend.clone()), @@ -395,13 +407,35 @@ fn compile_routing( normalize_prefix(&mut route.path_prefix)?; None } + crate::vhost::PathMatch::Any => { + route.path_prefix = "/".into(); + None + } }; - if !route.internal { + let route_conditions = crate::vhost::CompiledConditions::compile(&route.conditions) + .with_context(|| format!("vhost {} location {}", host.id, route.id))? + .map(Arc::new); + // Locations with conditions may share a path: the first whose conditions + // hold is used, the others are skipped. + if !route.internal && route.conditions.is_empty() { ensure!( path_bindings.insert((route.match_type, route.path_prefix.clone())), "location {}: another location already uses the same path and match type", route.id ); + } else if !route.internal + && matches!( + route.match_type, + crate::vhost::PathMatch::Regex | crate::vhost::PathMatch::RegexInsensitive + ) + { + // Regular expressions are tried in list order, so a conditional copy of an + // earlier unconditional pattern could never be reached. + ensure!( + !path_bindings.contains(&(route.match_type, route.path_prefix.clone())), + "location {}: an earlier location without conditions already uses this regular expression, so this one would never match; move it above that location", + route.id + ); } validate_route_rewrite(route, path_regex.as_ref())?; validate_location_response(route.response.as_ref())?; @@ -443,6 +477,22 @@ fn compile_routing( route.id ) })?; + let pool = if route.backend_ids.is_empty() + && route.load_balancing.is_none() + { + pool.clone() + } else { + Arc::new( + pool.derive( + &route.id, + &route.backend_ids, + route.load_balancing.as_ref(), + ) + .with_context(|| { + format!("vhost {} location {}", host.id, route.id) + })?, + ) + }; let backend = if let Some(id) = route.backend_id.as_deref() { pool.members .iter() @@ -452,11 +502,7 @@ fn compile_routing( } else { pool.members[0].backend.clone() }; - ( - CompiledSource::ReverseProxy, - Some(pool.clone()), - Some(backend), - ) + (CompiledSource::ReverseProxy, Some(pool), Some(backend)) } crate::vhost::Source::WebServer { web_service_id } => ( CompiledSource::WebServer(web_services[web_service_id].clone()), @@ -466,11 +512,18 @@ fn compile_routing( } }; let compiled = Arc::new(CompiledRoute { + conditions: route_conditions, backend_id: route.backend_id.clone(), bindings: frontend.bindings.clone(), frontend: Some(frontend.clone()), pool: route_pool, - cache: route.cache, + // Responses of a conditional location depend on request attributes + // outside the cache key, so they are never cached. + cache: if route.conditions.is_empty() { + route.cache + } else { + Some(false) + }, name: route.id.clone(), id: format!("{}/{}", host.id, route.id), internal: route.internal, diff --git a/src/config/routing_conditions_tests.rs b/src/config/routing_conditions_tests.rs new file mode 100644 index 0000000..d3b5179 --- /dev/null +++ b/src/config/routing_conditions_tests.rs @@ -0,0 +1,159 @@ +#[cfg(test)] +mod routing_conditions_tests { + use super::*; + + const FIXTURE: &str = include_str!("../../tests/fixtures/routing_conditions_cases.json"); + + fn policy() -> ValidationPolicy { + ValidationPolicy { + proxy_addr: "127.0.0.1:8080".parse().unwrap(), + admin_addr: "127.0.0.1:9090".parse().unwrap(), + tls_addr: None, + cert_dir: None, + data_dir: None, + } + } + fn config(vhost: serde_json::Value) -> anyhow::Result { + let cfg = serde_json::from_value(serde_json::json!({ + "listeners":{"endpoints":[{"id":"http","binding":{"address":"127.0.0.1:8080"}}]}, + "vhosts":[vhost] + }))?; + compile(cfg, 0, &policy()) + } + + /// Shared with tools/dev/test_routing_tester.js (panel tester parity). + #[test] + fn fixture_cases_select_the_expected_location() { + let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap(); + let snapshot = config(fixture["vhost"].clone()).unwrap(); + let local: std::net::SocketAddr = "127.0.0.1:8080".parse().unwrap(); + for case in fixture["cases"].as_array().unwrap() { + let name = case["name"].as_str().unwrap(); + let method: http::Method = case["method"].as_str().unwrap_or("GET").parse().unwrap(); + let host = case["host"].as_str().unwrap_or("site.test"); + let path = case["path"].as_str().unwrap(); + let mut headers = http::HeaderMap::new(); + if let Some(map) = case["headers"].as_object() { + for (key, value) in map { + headers.insert( + http::HeaderName::from_bytes(key.as_bytes()).unwrap(), + value.as_str().unwrap().parse().unwrap(), + ); + } + } + let facts = crate::vhost::RouteRequest { + method: &method, + headers: &headers, + query: case["query"].as_str(), + host, + client_ip: case["client_ip"].as_str().unwrap_or("203.0.113.5").parse().unwrap(), + country: case["country"].as_str(), + }; + let route = snapshot + .select_on_request(host, path, local, false, Some(&facts)) + .unwrap_or_else(|| panic!("{name}: no route")); + assert_eq!(route.name, case["expect"].as_str().unwrap(), "{name}"); + } + } + + #[test] + fn conditional_locations_are_skipped_without_request_facts_and_never_cached() { + let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap(); + let snapshot = config(fixture["vhost"].clone()).unwrap(); + let local: std::net::SocketAddr = "127.0.0.1:8080".parse().unwrap(); + let route = snapshot.select_on("site.test", "/api/x", local, false).unwrap(); + assert_eq!(route.name, "api"); + let route = snapshot.select_on("site.test", "/a.mp3", local, false).unwrap(); + assert_eq!(route.name, "mp3"); + let frontend = snapshot.frontend("site.test", local, false).unwrap(); + assert!(frontend.conditional_routes); + assert!(frontend.route_conditions_country); + let fixture_routes = fixture["vhost"]["routes"].as_array().unwrap(); + let conditional = fixture_routes + .iter() + .filter(|r| r.get("conditions").is_some()) + .count(); + assert!(conditional >= 5); + // A conditional location never uses the cache. + let headers = { + let mut h = http::HeaderMap::new(); + h.insert("x-beta", "1".parse().unwrap()); + h + }; + let facts = crate::vhost::RouteRequest { + method: &http::Method::GET, + headers: &headers, + query: None, + host: "site.test", + client_ip: "203.0.113.5".parse().unwrap(), + country: None, + }; + let beta = snapshot + .select_on_request("site.test", "/api/x", local, false, Some(&facts)) + .unwrap(); + assert_eq!(beta.name, "api-beta"); + assert_eq!(beta.cache, Some(false)); + assert_eq!(beta.pool.as_ref().unwrap().members.len(), 1); + } + + #[test] + fn invalid_conditions_are_rejected() { + let vhost = |routes: serde_json::Value| { + serde_json::json!({ + "id":"v","frontend":{"hosts":["v.test"],"listener_ids":["http"]}, + "backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}], + "load_balancing":{"health_check":{"mode":"off"}}, + "routes":routes + }) + }; + for routes in [ + serde_json::json!([{"id":"x","match_type":"any"}]), + serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","values":["1"]}]}]), + serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"bad name","values":["1"]}]}]), + serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"ip","values":["10.0.0.0/8"]}]}]), + serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"ip","operator":"cidr","values":["nope"]}]}]), + serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"method","operator":"prefix","values":["GE"]}]}]), + serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"country","values":["POL"]}]}]), + serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"a","operator":"exists","values":["1"]}]}]), + serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"a","operator":"regex","values":["("]}]}]), + serde_json::json!([{"id":"x","path_prefix":"/x","conditions":[{"source":"header","name":"a","values":[]}]}]), + serde_json::json!([{"id":"x","path_prefix":"/x","cache":true,"conditions":[{"source":"method","values":["GET"]}]}]), + serde_json::json!([{"id":"x","internal":true,"conditions":[{"source":"method","values":["GET"]}]}]), + serde_json::json!([ + {"id":"x","match_type":"regex","path_prefix":"\\.js$"}, + {"id":"y","match_type":"regex","path_prefix":"\\.js$","conditions":[{"source":"method","values":["GET"]}]} + ]), + serde_json::json!([ + {"id":"x","path_prefix":"/x"}, + {"id":"y","path_prefix":"/x"} + ]), + ] { + assert!(config(vhost(routes.clone())).is_err(), "{routes} should be rejected"); + } + // A conditional copy before the unconditional regex is fine, and two + // conditional prefixes may share a path. + assert!(config(vhost(serde_json::json!([ + {"id":"y","match_type":"regex","path_prefix":"\\.js$","conditions":[{"source":"method","values":["GET"]}]}, + {"id":"x","match_type":"regex","path_prefix":"\\.js$"}, + {"id":"p1","path_prefix":"/p","conditions":[{"source":"header","name":"a","operator":"exists"}]}, + {"id":"p2","path_prefix":"/p","conditions":[{"source":"header","name":"b","operator":"exists"}]} + ]))) + .is_ok()); + } + + #[test] + fn legacy_routes_serialize_without_new_fields() { + let route: crate::vhost::PathRoute = + serde_json::from_value(serde_json::json!({"id":"a","path_prefix":"/a"})).unwrap(); + let value = serde_json::to_value(&route).unwrap(); + for key in ["conditions", "backend_ids", "load_balancing"] { + assert!(value.get(key).is_none(), "{key} should be omitted"); + } + let condition: crate::vhost::RouteCondition = serde_json::from_value( + serde_json::json!({"source":"header","name":"X-A","values":["1"]}), + ) + .unwrap(); + let value = serde_json::to_value(&condition).unwrap(); + assert!(value.get("negate").is_none() && value.get("ignore_case").is_none()); + } +} diff --git a/src/config/snapshot.rs b/src/config/snapshot.rs index 8396d48..14cda66 100644 --- a/src/config/snapshot.rs +++ b/src/config/snapshot.rs @@ -71,6 +71,17 @@ impl Snapshot { path: &str, local: SocketAddr, tls: bool, + ) -> Option<&Arc> { + self.select_on_request(host, path, local, tls, None) + } + /// Route selection with request facts, so locations with conditions can match. + pub fn select_on_request( + &self, + host: &str, + path: &str, + local: SocketAddr, + tls: bool, + request: Option<&crate::vhost::RouteRequest<'_>>, ) -> Option<&Arc> { Self::find_host_pattern(host, |pattern| { let fallback = self.fallbacks.get(pattern).and_then(|routes| { @@ -81,9 +92,12 @@ impl Snapshot { self.routes .get(pattern) .and_then(|routes| { - select_route(routes, path, |r| { - r.bindings.iter().any(|l| l.matches(local, tls)) - }) + select_route( + routes, + path, + |r| r.bindings.iter().any(|l| l.matches(local, tls)), + request, + ) }) .or(Some(fallback)) }) @@ -263,7 +277,7 @@ impl Snapshot { .and_then(|routes| routes.first())?; self.routes .get(pattern) - .and_then(|routes| select_route(routes, path, |_| true)) + .and_then(|routes| select_route(routes, path, |_| true, None)) .or(Some(fallback)) .map(Arc::as_ref) }) @@ -276,48 +290,77 @@ fn host_pattern_rank(pattern: &str, host: &str) -> usize { pattern.len() } } +/// Location selection. Order: exact → prefix-priority → regex and any-path rules (list +/// order) → longest prefix. A location with `conditions` is a candidate only when all of +/// them hold for `request`; without request facts (cache refresh, early response +/// handling) conditional locations are skipped. Among equal candidates a conditional +/// location wins over an unconditional one (exact paths, prefixes of equal length). fn select_route<'a, F>( routes: &'a [Arc], path: &str, allowed: F, + request: Option<&crate::vhost::RouteRequest<'_>>, ) -> Option<&'a Arc> where F: Fn(&CompiledRoute) -> bool, { - if let Some(exact) = routes.iter().find(|route| { + let usable = |route: &CompiledRoute| { !route.internal && allowed(route) - && route.match_type == crate::vhost::PathMatch::Exact + && route + .conditions + .as_ref() + .is_none_or(|conditions| request.is_some_and(|r| conditions.matches(r))) + }; + let exact = |route: &&Arc| { + route.match_type == crate::vhost::PathMatch::Exact && route.path_prefix == path - }) { + && usable(route) + }; + if let Some(exact) = routes + .iter() + .filter(|route| route.conditions.is_some()) + .find(exact) + .or_else(|| routes.iter().find(exact)) + { return Some(exact); } - let prefix = routes - .iter() - .filter(|route| { - !route.internal - && allowed(route) - && matches!( - route.match_type, - crate::vhost::PathMatch::Prefix | crate::vhost::PathMatch::PrefixPriority - ) - && prefix_matches(&route.path_prefix, path) - }) - .max_by_key(|route| route.path_prefix.len()); + let mut prefix: Option<&Arc> = None; + for route in routes { + if !matches!( + route.match_type, + crate::vhost::PathMatch::Prefix | crate::vhost::PathMatch::PrefixPriority + ) || !prefix_matches(&route.path_prefix, path) + || !usable(route) + { + continue; + } + let better = match prefix { + None => true, + Some(best) => { + route.path_prefix.len() > best.path_prefix.len() + || (route.path_prefix.len() == best.path_prefix.len() + && route.conditions.is_some() + && best.conditions.is_none()) + } + }; + if better { + prefix = Some(route); + } + } if prefix.is_some_and(|route| route.match_type == crate::vhost::PathMatch::PrefixPriority) { return prefix; } if let Some(regex) = routes.iter().find(|route| { - !route.internal - && allowed(route) - && matches!( - route.match_type, - crate::vhost::PathMatch::Regex | crate::vhost::PathMatch::RegexInsensitive - ) - && route + let path_matches = match route.match_type { + crate::vhost::PathMatch::Regex | crate::vhost::PathMatch::RegexInsensitive => route .path_regex .as_ref() - .is_some_and(|regex| regex.is_match(path)) + .is_some_and(|regex| regex.is_match(path)), + crate::vhost::PathMatch::Any => true, + _ => false, + }; + path_matches && usable(route) }) { return Some(regex); } diff --git a/src/proxy/body/mod.rs b/src/proxy/body/mod.rs index d50d006..314756c 100644 --- a/src/proxy/body/mod.rs +++ b/src/proxy/body/mod.rs @@ -53,6 +53,9 @@ pub struct Exchange { pub vhost_metrics: Option>, pub vhost: Option, pub route: Mutex>, + /// Location chosen by conditional routing when it differs from the route the + /// response layer saw before the request was forwarded. + pub routed: Mutex>>, pub source: AtomicU8, pub cache_effective_enabled: AtomicU8, pub transform_effective_enabled: AtomicU8, diff --git a/src/proxy/body/tests.rs b/src/proxy/body/tests.rs index 2faadab..aa0357f 100644 --- a/src/proxy/body/tests.rs +++ b/src/proxy/body/tests.rs @@ -11,6 +11,7 @@ mod tests { vhost_metrics: None, vhost: None, route: Mutex::new(None), + routed: Mutex::new(None), source: AtomicU8::new(ExchangeSource::Unresolved as u8), cache_effective_enabled: AtomicU8::new(0), transform_effective_enabled: AtomicU8::new(0), diff --git a/src/proxy/forward/route_cache.rs b/src/proxy/forward/route_cache.rs index eef4bbb..79f35e9 100644 --- a/src/proxy/forward/route_cache.rs +++ b/src/proxy/forward/route_cache.rs @@ -49,7 +49,7 @@ let (backend, backend_lease, affinity_cookie) = if let Some(pool) = &route.pool let selection = match &route.backend_id { Some(id) => pool.select_member_wait(id).await, None => pool - .select_wait(context.client_ip, request.headers(), tls) + .select_wait_uri(context.client_ip, request.headers(), balance_uri.as_ref(), tls) .await, }; let selection = match selection { diff --git a/src/proxy/forward/upstream.rs b/src/proxy/forward/upstream.rs index dcf7c49..d12848c 100644 --- a/src/proxy/forward/upstream.rs +++ b/src/proxy/forward/upstream.rs @@ -213,9 +213,10 @@ let upstream_result = loop { break result; }; let selection = match pool - .select_retry_wait( + .select_retry_wait_uri( context.client_ip, retry_headers, + balance_uri.as_ref(), tls, &attempted_backends, ) diff --git a/src/proxy/forward_entry.rs b/src/proxy/forward_entry.rs index 1e76a21..f21330e 100644 --- a/src/proxy/forward_entry.rs +++ b/src/proxy/forward_entry.rs @@ -312,7 +312,8 @@ async fn forward_request( .profile_policies .iter() .any(|profile| profile.countries.needs_geoip()) - || frontend.rate_limit.needs_geoip()) + || frontend.rate_limit.needs_geoip() + || frontend.route_conditions_country) { country = cloudflare_country .clone() @@ -437,6 +438,32 @@ async fn forward_request( } else { snapshot.select_internal_on(&host, &dispatch.vhost_id, &dispatch.target, local.0, tls) } + } else if frontend.is_some_and(|frontend| frontend.conditional_routes) { + // Locations with request conditions are selected here, with the final client + // address and country; earlier stages only saw unconditional locations. + let facts = crate::vhost::RouteRequest { + method: request.method(), + headers: request.headers(), + query: request.uri().query(), + host: &host, + client_ip: context.client_ip, + country: country.as_deref(), + }; + let chosen = snapshot.select_on_request(&host, &path, local.0, tls, Some(&facts)); + if let (Some(chosen), Some(exchange)) = + (chosen, request.extensions().get::>()) + { + let precomputed = selected_context + .as_ref() + .and_then(|selection| selection.route.as_ref()); + if precomputed.is_none_or(|route| !Arc::ptr_eq(route, chosen)) { + *exchange + .routed + .lock() + .unwrap_or_else(|e| e.into_inner()) = Some(chosen.clone()); + } + } + chosen.map(Arc::as_ref) } else if let Some(selection) = &selected_context { selection.route.as_deref() } else { @@ -559,6 +586,13 @@ async fn forward_request( ) }); }; + // Client URI as received (before location rewrites and cache-rule query changes), + // kept only for pools that hash the path, URI, host or a query parameter. + let balance_uri = route + .pool + .as_ref() + .is_some_and(|pool| pool.hashes_request_uri()) + .then(|| request.uri().clone()); let fallback_body = match prepare_error_fallback_body(&mut request, route.error_fallback.is_some()).await { Ok(body) => body, diff --git a/src/proxy/upstream_helpers.rs b/src/proxy/upstream_helpers.rs index 6358cf9..9fd9ff2 100644 --- a/src/proxy/upstream_helpers.rs +++ b/src/proxy/upstream_helpers.rs @@ -215,6 +215,7 @@ async fn observe(state: Arc, mut request: Request) -> Response { vhost_metrics: frontend_context.as_ref().map(|f| f.metrics.clone()), vhost: frontend_context.as_ref().map(|f| f.id.clone()), route: Mutex::new(None), + routed: Mutex::new(None), source: AtomicU8::new(ExchangeSource::Unresolved as u8), cache_effective_enabled: AtomicU8::new(0), transform_effective_enabled: AtomicU8::new(0), @@ -262,8 +263,14 @@ async fn observe(state: Arc, mut request: Request) -> Response { .extensions() .get::() .map(|context| context.0.clone()); + let routed_context = exchange + .routed + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone(); let effective_route_context = final_route_context .as_deref() + .or(routed_context.as_deref()) .or(route_context.as_deref()); let minimal_welcome = response .extensions() diff --git a/src/vhost.rs b/src/vhost.rs index f8074f9..46e0952 100644 --- a/src/vhost.rs +++ b/src/vhost.rs @@ -1,4 +1,5 @@ include!("vhost/model.rs"); +include!("vhost/conditions.rs"); include!("vhost/error_fallback.rs"); include!("vhost/redirect.rs"); include!("vhost/validation.rs"); diff --git a/src/vhost/conditions.rs b/src/vhost/conditions.rs new file mode 100644 index 0000000..5bf23d6 --- /dev/null +++ b/src/vhost/conditions.rs @@ -0,0 +1,351 @@ +// Request conditions of a location (routing rules beyond the path). All conditions of +// a location must hold (AND); each condition matches when any of its values matches +// (OR); `negate` inverts one condition. Locations that do not match are skipped and +// selection continues with the next candidate, so "OR" between rules is written as +// several locations. + +/// Request attribute tested by a [`RouteCondition`]. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)] +#[serde(rename_all = "snake_case")] +pub enum ConditionSource { + #[default] + Header, + Cookie, + Query, + Method, + /// Client address as determined by RustProxy (trusted forwarding / Cloudflare). + Ip, + /// Request host name without port (useful with wildcard vhosts). + Host, + /// ISO country code from the GeoIP database or Cloudflare. + Country, +} +impl ConditionSource { + pub fn needs_name(self) -> bool { + matches!(self, Self::Header | Self::Cookie | Self::Query) + } +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, Default)] +#[serde(rename_all = "snake_case")] +pub enum ConditionOperator { + #[default] + Equals, + Exists, + Prefix, + Suffix, + Contains, + Regex, + /// IP address or CIDR network (only for `ip`). + Cidr, +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(default, deny_unknown_fields)] +pub struct RouteCondition { + pub source: ConditionSource, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + pub operator: ConditionOperator, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub values: Vec, + #[serde(skip_serializing_if = "is_false")] + pub negate: bool, + #[serde(skip_serializing_if = "is_false")] + pub ignore_case: bool, +} + +pub const MAX_ROUTE_CONDITIONS: usize = 16; +const MAX_CONDITION_VALUES: usize = 64; + +impl RouteCondition { + pub fn validate(&self) -> Result<()> { + self.compile().map(|_| ()) + } + pub fn compile(&self) -> Result { + use ConditionOperator as Op; + use ConditionSource as Src; + let name = self.name.as_deref().unwrap_or("").trim(); + if self.source.needs_name() { + ensure!( + !name.is_empty() && name.len() <= 128, + "condition on {:?} needs a name (1..128 characters)", + self.source + ); + if self.source == Src::Header { + ensure!( + http::HeaderName::from_bytes(name.as_bytes()).is_ok(), + "condition header name {name:?} is not a valid HTTP header name" + ); + } else { + ensure!( + name.bytes() + .all(|b| b.is_ascii_graphic() && !matches!(b, b';' | b'=' | b'&' | b',')), + "condition cookie/query name must be printable ASCII without ; = & or ," + ); + } + } else { + ensure!( + name.is_empty(), + "a name is only used by header, cookie and query conditions" + ); + } + let allowed = match self.source { + Src::Ip => matches!(self.operator, Op::Cidr), + Src::Method | Src::Country => matches!(self.operator, Op::Equals), + Src::Host => !matches!(self.operator, Op::Cidr | Op::Exists), + Src::Header | Src::Cookie | Src::Query => !matches!(self.operator, Op::Cidr), + }; + ensure!( + allowed, + "operator {:?} cannot be used with a {:?} condition", + self.operator, + self.source + ); + let values: Vec = self.values.iter().map(|v| v.trim().to_owned()).collect(); + if self.operator == Op::Exists { + ensure!(values.is_empty(), "an exists condition takes no values"); + } else { + ensure!( + (1..=MAX_CONDITION_VALUES).contains(&values.len()), + "condition needs 1..{MAX_CONDITION_VALUES} values" + ); + for value in &values { + ensure!( + !value.is_empty() && value.len() <= 1024 && !value.chars().any(char::is_control), + "condition values must be 1..1024 characters without control characters" + ); + } + } + let fold = (self.ignore_case && self.source.needs_name()) || self.source == Src::Host; + let matcher = match self.operator { + Op::Exists => Matcher::Exists, + Op::Cidr => Matcher::Cidr( + values + .iter() + .map(|value| { + value + .parse::() + .or_else(|_| value.parse::().map(ipnet::IpNet::from)) + .map(|net| net.trunc()) + .map_err(|_| anyhow::anyhow!("invalid IP address or CIDR {value:?}")) + }) + .collect::>()?, + ), + Op::Regex => Matcher::Regex( + values + .iter() + .map(|value| { + regex::RegexBuilder::new(value) + .case_insensitive(fold) + .size_limit(1024 * 1024) + .dfa_size_limit(1024 * 1024) + .build() + .map_err(|_| anyhow::anyhow!("invalid or too complex regular expression {value:?}")) + }) + .collect::>()?, + ), + op => { + let mut list = values.clone(); + match self.source { + Src::Method => { + for value in &mut list { + *value = value.to_ascii_uppercase(); + ensure!( + http::Method::from_bytes(value.as_bytes()).is_ok(), + "invalid HTTP method {value:?}" + ); + } + } + Src::Country => { + for value in &mut list { + *value = value.to_ascii_uppercase(); + ensure!( + value.len() == 2 && value.bytes().all(|b| b.is_ascii_uppercase()), + "country codes must be two letters (ISO 3166-1 alpha-2)" + ); + } + } + Src::Host => { + for value in &mut list { + *value = value.trim_end_matches('.').to_ascii_lowercase(); + } + } + _ => { + if fold { + for value in &mut list { + *value = value.to_lowercase(); + } + } + } + } + match op { + Op::Equals => Matcher::Equals(list), + Op::Prefix => Matcher::Prefix(list), + Op::Suffix => Matcher::Suffix(list), + _ => Matcher::Contains(list), + } + } + }; + Ok(CompiledCondition { + source: self.source, + name: (!name.is_empty()).then(|| name.to_owned()), + matcher, + negate: self.negate, + fold, + }) + } +} + +#[derive(Debug, Clone)] +enum Matcher { + Exists, + Equals(Vec), + Prefix(Vec), + Suffix(Vec), + Contains(Vec), + Regex(Vec), + Cidr(Vec), +} + +#[derive(Debug, Clone)] +pub struct CompiledCondition { + source: ConditionSource, + name: Option, + matcher: Matcher, + negate: bool, + fold: bool, +} + +/// Request attributes available to location conditions. +#[derive(Debug, Clone, Copy)] +pub struct RouteRequest<'a> { + pub method: &'a http::Method, + pub headers: &'a http::HeaderMap, + pub query: Option<&'a str>, + pub host: &'a str, + pub client_ip: IpAddr, + pub country: Option<&'a str>, +} + +impl CompiledCondition { + pub fn source(&self) -> ConditionSource { + self.source + } + fn values<'a>(&self, request: &RouteRequest<'a>) -> Vec> { + use std::borrow::Cow; + let name = self.name.as_deref().unwrap_or(""); + match self.source { + ConditionSource::Header => request + .headers + .get_all(name) + .iter() + .filter_map(|v| v.to_str().ok()) + .map(|v| Cow::Borrowed(v.trim())) + .collect(), + ConditionSource::Cookie => request + .headers + .get_all(http::header::COOKIE) + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(';')) + .filter_map(|pair| pair.trim().split_once('=')) + .filter(|(n, _)| *n == name) + .map(|(_, v)| Cow::Borrowed(v.trim())) + .collect(), + ConditionSource::Query => request + .query + .into_iter() + .flat_map(|q| q.split('&')) + .map(|pair| pair.split_once('=').unwrap_or((pair, ""))) + .filter(|(n, _)| *n == name) + .map(|(_, v)| Cow::Borrowed(v)) + .collect(), + ConditionSource::Method => vec![Cow::Borrowed(request.method.as_str())], + ConditionSource::Host => vec![Cow::Owned( + request.host.trim_end_matches('.').to_ascii_lowercase(), + )], + ConditionSource::Country => request + .country + .map(|c| Cow::Owned(c.to_ascii_uppercase())) + .into_iter() + .collect(), + ConditionSource::Ip => vec![Cow::Owned( + crate::vhost::canonical_ip(request.client_ip).to_string(), + )], + } + } + pub fn matches(&self, request: &RouteRequest<'_>) -> bool { + let raw = self.values(request); + let fold = |value: &str| -> String { + if self.fold && self.source != ConditionSource::Host { + value.to_lowercase() + } else { + value.to_owned() + } + }; + let hit = match &self.matcher { + Matcher::Exists => !raw.is_empty(), + Matcher::Cidr(nets) => { + let ip = crate::vhost::canonical_ip(request.client_ip); + nets.iter().any(|net| net.contains(&ip)) + } + Matcher::Regex(list) => raw.iter().any(|v| list.iter().any(|r| r.is_match(v))), + Matcher::Equals(list) => raw + .iter() + .any(|v| list.iter().any(|p| fold(v) == *p)), + Matcher::Prefix(list) => raw + .iter() + .any(|v| list.iter().any(|p| fold(v).starts_with(p.as_str()))), + Matcher::Suffix(list) => raw + .iter() + .any(|v| list.iter().any(|p| fold(v).ends_with(p.as_str()))), + Matcher::Contains(list) => raw + .iter() + .any(|v| list.iter().any(|p| fold(v).contains(p.as_str()))), + }; + hit != self.negate + } +} + +/// All conditions of one location. +#[derive(Debug, Clone, Default)] +pub struct CompiledConditions(Vec); +impl CompiledConditions { + pub fn compile(conditions: &[RouteCondition]) -> Result> { + ensure!( + conditions.len() <= MAX_ROUTE_CONDITIONS, + "at most {MAX_ROUTE_CONDITIONS} conditions per location" + ); + if conditions.is_empty() { + return Ok(None); + } + Ok(Some(Self( + conditions + .iter() + .enumerate() + .map(|(index, condition)| { + condition + .compile() + .with_context(|| format!("condition {}", index + 1)) + }) + .collect::>()?, + ))) + } + pub fn matches(&self, request: &RouteRequest<'_>) -> bool { + self.0.iter().all(|condition| condition.matches(request)) + } + /// Result of every condition, for the panel tester. + pub fn explain(&self, request: &RouteRequest<'_>) -> Vec { + self.0.iter().map(|condition| condition.matches(request)).collect() + } + pub fn needs_country(&self) -> bool { + self.0 + .iter() + .any(|condition| condition.source == ConditionSource::Country) + } +} diff --git a/src/vhost/model.rs b/src/vhost/model.rs index 4598ad5..e1d612d 100644 --- a/src/vhost/model.rs +++ b/src/vhost/model.rs @@ -238,6 +238,9 @@ pub enum PathMatch { Exact, Regex, RegexInsensitive, + /// Any path: a vhost-wide rule selected only by its `conditions`. Evaluated with + /// regex locations, in list order. + Any, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] #[serde(rename_all = "snake_case")] @@ -533,6 +536,16 @@ pub struct PathRoute { pub source: Source, #[serde(default, skip_serializing_if = "Option::is_none")] pub backend_id: Option, + /// Backend group of this location (ids of vhost backends). Empty: the vhost pool + /// (or `backend_id`). Like a HAProxy `use_backend` target sharing the vhost servers. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub backend_ids: Vec, + /// Location-specific balancing (algorithm, hash key, affinity) over its backends. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub load_balancing: Option, + /// Extra request conditions (all must hold) besides the path. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub conditions: Vec, pub id: String, #[serde(default)] pub internal: bool, diff --git a/src/vhost/validation.rs b/src/vhost/validation.rs index f9f2c82..fb8c3ce 100644 --- a/src/vhost/validation.rs +++ b/src/vhost/validation.rs @@ -3,6 +3,9 @@ impl Default for PathRoute { Self { source: Source::default(), backend_id: None, + backend_ids: Vec::new(), + load_balancing: None, + conditions: Vec::new(), id: "root".into(), internal: false, path_prefix: root(), @@ -29,6 +32,9 @@ impl PathRoute { && self.enabled && self.source == Source::ReverseProxy && self.backend_id.is_none() + && self.backend_ids.is_empty() + && self.load_balancing.is_none() + && self.conditions.is_empty() && !self.internal && self.cache.is_none() && self.acl_profile_id.is_none() @@ -175,9 +181,70 @@ impl Vhost { route.country_access.validate()?; route.method_policy.validate()?; ensure!( - route.source.is_reverse_proxy() || route.backend_id.is_none(), - "Web Server location cannot pin a reverse-proxy backend" + route.source.is_reverse_proxy() + || (route.backend_id.is_none() + && route.backend_ids.is_empty() + && route.load_balancing.is_none()), + "Web Server location cannot pin a reverse-proxy backend or balancing" ); + ensure!( + route.backend_id.is_none() + || (route.backend_ids.is_empty() && route.load_balancing.is_none()), + "location {}: a pinned backend cannot be combined with a backend group or location balancing", + route.id + ); + ensure!( + route.backend_ids.len() <= 64, + "location {}: at most 64 backends in a location backend group", + route.id + ); + { + let mut seen = std::collections::HashSet::new(); + for id in &route.backend_ids { + ensure!( + crate::config::valid_id(id) && seen.insert(id.as_str()), + "location {}: backend group id {:?} is invalid or listed twice", + route.id, + id + ); + ensure!( + self.backends.iter().any(|b| &b.id == id), + "location {}: backend group references unknown backend {}", + route.id, + id + ); + } + } + ensure!( + route.conditions.len() <= MAX_ROUTE_CONDITIONS, + "location {}: at most {MAX_ROUTE_CONDITIONS} conditions", + route.id + ); + for (index, condition) in route.conditions.iter().enumerate() { + condition.validate().map_err(|e| { + anyhow::anyhow!("location {} condition {}: {e}", route.id, index + 1) + })?; + } + ensure!( + route.match_type != PathMatch::Any || !route.conditions.is_empty(), + "location {}: an any-path (vhost-wide) rule needs at least one condition", + route.id + ); + ensure!( + !route.internal || route.conditions.is_empty(), + "location {}: internal locations cannot have conditions", + route.id + ); + ensure!( + route.conditions.is_empty() || route.cache != Some(true), + "location {}: locations with conditions are never cached (their responses depend on request attributes outside the cache key); leave cache on inherit or off", + route.id + ); + if let Some(balancing) = &route.load_balancing { + balancing.validate().map_err(|e| { + anyhow::anyhow!("location {}: {e}", route.id) + })?; + } if let Some(fallback) = &mut route.error_fallback { fallback.validate()?; } diff --git a/tests/fixtures/balance_rendezvous_vectors.txt b/tests/fixtures/balance_rendezvous_vectors.txt new file mode 100644 index 0000000..7265d2c --- /dev/null +++ b/tests/fixtures/balance_rendezvous_vectors.txt @@ -0,0 +1 @@ +/a.mp3=s1,s3,s2;/music/b.mp3=s1,s3,s2;/c=s1,s2,s3;tenant-42=s3,s1,s2;192.0.2.10=s3,s2,s1 diff --git a/tests/fixtures/routing_conditions_cases.json b/tests/fixtures/routing_conditions_cases.json new file mode 100644 index 0000000..0f26159 --- /dev/null +++ b/tests/fixtures/routing_conditions_cases.json @@ -0,0 +1,55 @@ +{ + "vhost": { + "id": "site", + "frontend": {"hosts": ["site.test", "*.site.test"], "listener_ids": ["http"]}, + "backends": [ + {"id": "app", "url": "http://127.0.0.1:9000", "allow_private": true}, + {"id": "beta", "url": "http://127.0.0.1:9001", "allow_private": true, "pool_eligible": false}, + {"id": "office", "url": "http://127.0.0.1:9002", "allow_private": true, "pool_eligible": false}, + {"id": "mp3_1", "url": "http://127.0.0.1:9011", "allow_private": true, "pool_eligible": false}, + {"id": "mp3_2", "url": "http://127.0.0.1:9012", "allow_private": true, "pool_eligible": false} + ], + "load_balancing": {"health_check": {"mode": "off"}}, + "routes": [ + {"id": "health", "match_type": "exact", "path_prefix": "/health", "response": {"status": 200, "body": "ok"}}, + {"id": "health-post", "match_type": "exact", "path_prefix": "/health", + "conditions": [{"source": "method", "values": ["POST", "put"]}], "response": {"status": 405, "body": "no"}}, + {"id": "api-beta", "path_prefix": "/api/", "backend_ids": ["beta"], + "conditions": [{"source": "header", "name": "X-Beta", "values": ["1", "yes"], "ignore_case": true}]}, + {"id": "api", "path_prefix": "/api/"}, + {"id": "api-v2-tenant", "path_prefix": "/api/v2/", "backend_ids": ["beta"], + "conditions": [{"source": "query", "name": "tenant", "operator": "prefix", "values": ["test-"]}]}, + {"id": "office", "match_type": "any", "backend_ids": ["office"], + "conditions": [{"source": "ip", "operator": "cidr", "values": ["10.0.0.0/8", "192.0.2.7"]}, + {"source": "cookie", "name": "staff", "operator": "exists"}]}, + {"id": "mp3-eu", "match_type": "regex_insensitive", "path_prefix": "\\.mp3$", "backend_ids": ["mp3_1"], + "conditions": [{"source": "country", "values": ["pl", "DE"]}]}, + {"id": "mp3", "match_type": "regex_insensitive", "path_prefix": "\\.mp3$", "backend_ids": ["mp3_1", "mp3_2"], + "load_balancing": {"algorithm": "hash"}}, + {"id": "not-bot", "match_type": "any", "backend_ids": ["beta"], + "conditions": [{"source": "host", "operator": "suffix", "values": [".beta.site.test"]}, + {"source": "header", "name": "User-Agent", "operator": "regex", "values": ["(?i)bot"], "negate": true}]} + ] + }, + "cases": [ + {"name": "plain page goes to the vhost pool", "path": "/index.html", "expect": "main"}, + {"name": "exact unconditional", "path": "/health", "expect": "health"}, + {"name": "exact with method condition wins", "method": "POST", "path": "/health", "expect": "health-post"}, + {"name": "method values are case-insensitive", "method": "PUT", "path": "/health", "expect": "health-post"}, + {"name": "api without header", "path": "/api/users", "expect": "api"}, + {"name": "api with header", "path": "/api/users", "headers": {"x-beta": "YES"}, "expect": "api-beta"}, + {"name": "api with other header value", "path": "/api/users", "headers": {"x-beta": "0"}, "expect": "api"}, + {"name": "longer prefix with query condition", "path": "/api/v2/items", "query": "tenant=test-acme", "expect": "api-v2-tenant"}, + {"name": "longer prefix condition fails, falls back to shorter prefix", "path": "/api/v2/items", "query": "tenant=acme", "expect": "api"}, + {"name": "any-path rule: office network with staff cookie", "path": "/index.html", "client_ip": "10.20.30.40", "headers": {"cookie": "a=1; staff=1"}, "expect": "office"}, + {"name": "any-path rule beats plain prefix like a regex", "path": "/api/users", "client_ip": "192.0.2.7", "headers": {"cookie": "staff="}, "expect": "office"}, + {"name": "any-path rule needs all conditions", "path": "/index.html", "client_ip": "10.20.30.40", "expect": "main"}, + {"name": "exact still wins over any-path rule", "path": "/health", "client_ip": "10.1.1.1", "headers": {"cookie": "staff=1"}, "expect": "health"}, + {"name": "regex with country", "path": "/m/song.MP3", "country": "PL", "expect": "mp3-eu"}, + {"name": "regex country miss", "path": "/m/song.mp3", "country": "US", "expect": "mp3"}, + {"name": "regex without country", "path": "/m/song.mp3", "expect": "mp3"}, + {"name": "host suffix with negated user agent", "host": "x.beta.site.test", "path": "/", "headers": {"user-agent": "Mozilla/5.0"}, "expect": "not-bot"}, + {"name": "negated condition blocks bots", "host": "x.beta.site.test", "path": "/", "headers": {"user-agent": "Googlebot/2.1"}, "expect": "main"}, + {"name": "host condition miss", "host": "site.test", "path": "/", "expect": "main"} + ] +} diff --git a/tools/dev/test_balance_simulator.js b/tools/dev/test_balance_simulator.js new file mode 100644 index 0000000..09eb928 --- /dev/null +++ b/tools/dev/test_balance_simulator.js @@ -0,0 +1,60 @@ +#!/usr/bin/env node +"use strict"; +// Checks that the panel's consistent-hash simulator (src/admin/web/vhosts/balancing.js) +// ranks backends exactly like the proxy (src/balance/model.rs). The reference +// vectors come from the Rust test `rendezvous_reference_vectors`. +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); +const crypto = require("node:crypto"); +const assert = require("node:assert/strict"); + +const root = path.resolve(__dirname, "../.."); +const source = fs.readFileSync(path.join(root, "src/admin/web/vhosts/balancing.js"), "utf8"); +const sandbox = { window: {}, TextEncoder, BigInt, Math, Number, Uint8Array, Uint32Array, DataView }; +vm.runInNewContext(source, sandbox, { filename: "balancing.js" }); +const core = sandbox.window.rustProxyBalancingCore; +assert.equal(typeof core?.score, "function"); + +for (const input of ["", "abc", "a".repeat(55), "a".repeat(56), "a".repeat(64), "zażółć|/music/ü.mp3|s1", "x".repeat(1000)]) { + const expected = crypto.createHash("sha256").update(input, "utf8").digest("hex"); + const actual = Buffer.from(core.sha256(new TextEncoder().encode(input))).toString("hex"); + assert.equal(actual, expected, `sha256 mismatch for length ${input.length}`); +} + +const members = [{ id: "s1", weight: 1 }, { id: "s2", weight: 1 }, { id: "s3", weight: 2 }]; +const rendered = ["/a.mp3", "/music/b.mp3", "/c", "tenant-42", "192.0.2.10"] + .map(key => `${key}=${core.rank("files", key, members).map(m => m.id).join(",")}`).join(";"); +const expected = fs.readFileSync(path.join(root, "tests/fixtures/balance_rendezvous_vectors.txt"), "utf8").trim(); +assert.equal(rendered, expected, "simulator ranking differs from the proxy"); + +const key = (settings, line) => core.hashKey(settings, line); +assert.equal(key({ source: "path" }, "/music/Album/track.MP3?user=42&x"), "/music/Album/track.MP3"); +assert.equal(key({ source: "path", ignore_case: true }, "/music/Album/track.MP3"), "/music/album/track.mp3"); +assert.equal(key({ source: "path", path_depth: 1 }, "/music/Album/track.MP3"), "/music"); +assert.equal(key({ source: "path", path_depth: 2 }, "https://cdn.example.com/music/Album/track.MP3"), "/music/Album"); +assert.equal(key({ source: "uri" }, "/music/a.mp3?user=42&x"), "/music/a.mp3?user=42&x"); +assert.equal(key({ source: "host" }, "https://Files.Example.com:8443/x"), "files.example.com"); +assert.equal(key({ source: "host" }, "https://[2001:db8::1]:443/x"), "2001:db8::1"); +assert.equal(key({ source: "query", name: "user" }, "/x?user=42&x"), "42"); +assert.equal(key({ source: "query", name: "x" }, "/x?user=42&x"), null); +assert.equal(key({ source: "query", name: "user" }, "/x"), null); +assert.equal(key({ source: "cookie", name: "sid" }, "ABC"), "ABC"); +assert.equal(key({ source: "ip" }, " 203.0.113.9 "), "203.0.113.9"); + +// Removing a backend moves only its own keys. +const pool = [ + { id: "a", weight: 1, enabled: true, drain: false, backup: false, pool_eligible: false }, + { id: "b", weight: 1, enabled: true, drain: false, backup: false, pool_eligible: false }, + { id: "c", weight: 1, enabled: true, drain: false, backup: false, pool_eligible: false }, +]; +const samples = Array.from({ length: 300 }, (_, n) => `/f/${n}`); +assert.equal(core.simulate({ poolId: "v", settings: { source: "path" }, members: pool, samples }).filter(r => r.member).length, 0, + "location-only members are not used by the vhost pool"); +const rows = core.simulate({ poolId: "v", settings: { source: "path" }, members: pool, explicit: true, samples, down: new Set(["b"]) }); +for (const row of rows) { + if (row.previous === "b") assert.notEqual(row.member, "b"); + else assert.equal(row.member, row.previous); +} +assert.ok(rows.some(row => row.previous === "b")); +console.log("balance simulator: ok"); diff --git a/tools/dev/test_routing_tester.js b/tools/dev/test_routing_tester.js new file mode 100644 index 0000000..ff28e17 --- /dev/null +++ b/tools/dev/test_routing_tester.js @@ -0,0 +1,35 @@ +#!/usr/bin/env node +"use strict"; +// Checks that the panel routing tester (src/admin/web/vhosts/routing.js) selects the +// same location as the proxy for tests/fixtures/routing_conditions_cases.json, which +// the Rust test `fixture_cases_select_the_expected_location` also uses. +const fs = require("node:fs"); +const path = require("node:path"); +const vm = require("node:vm"); +const assert = require("node:assert/strict"); + +const root = path.resolve(__dirname, "../.."); +const sandbox = { window: {}, BigInt, RegExp, Math, Number, String, Array, Boolean }; +vm.runInNewContext(fs.readFileSync(path.join(root, "src/admin/web/vhosts/routing.js"), "utf8"), sandbox, { filename: "routing.js" }); +const core = sandbox.window.rustProxyRoutingCore; +assert.equal(typeof core?.evaluate, "function"); + +const fixture = JSON.parse(fs.readFileSync(path.join(root, "tests/fixtures/routing_conditions_cases.json"), "utf8")); +for (const item of fixture.cases) { + const request = { + method: item.method || "GET", path: item.path, query: item.query ?? null, host: item.host || "site.test", + client_ip: item.client_ip || "203.0.113.5", country: item.country || null, + headers: Object.entries(item.headers || {}), + }; + const { winner } = core.evaluate(fixture.vhost.routes, request); + assert.equal(winner ? winner.route.id : "main", item.expect, item.name); +} + +const cidr = core.cidrContains; +assert.ok(cidr("10.0.0.0/8", "10.200.1.1")); +assert.ok(!cidr("10.0.0.0/8", "11.0.0.1")); +assert.ok(cidr("2001:db8::/32", "2001:db8:1::5")); +assert.ok(!cidr("2001:db8::/32", "2001:db9::1")); +assert.ok(cidr("192.0.2.7", "::ffff:192.0.2.7"), "IPv4-mapped addresses are compared as IPv4"); +assert.ok(cidr("::1", "::1")); +console.log(`routing tester: ok (${fixture.cases.length} cases)`);