diff --git a/Cargo.lock b/Cargo.lock index dd82a7b..b5c6c56 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -130,7 +130,7 @@ checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" [[package]] name = "aralez" -version = "0.95.2" +version = "0.95.4" dependencies = [ "ahash", "anyhow", @@ -144,6 +144,7 @@ dependencies = [ "bytes", "dashmap 7.0.0-rc2", "elasticsearch", + "foyer", "futures", "hickory-resolver", "http-body-util", @@ -336,6 +337,12 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "asyncband" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d2050892d4691cf110586070786712b504985a4d37ed64a9cd8a402718e1706" + [[package]] name = "atomic-waker" version = "1.1.2" @@ -877,6 +884,15 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + [[package]] name = "bit-vec" version = "0.9.1" @@ -1194,6 +1210,17 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_affinity" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a034b3a7b624016c6e13f5df875747cc25f884156aad2abd12b6c46797971342" +dependencies = [ + "libc", + "num_cpus", + "winapi", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1452,6 +1479,12 @@ version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" +[[package]] +name = "datasketches" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c4cf71a36b46dcfc00e5014c0c20ccad2b1b6a008304d7d57d2749b2d41b3d" + [[package]] name = "defmt" version = "1.1.1" @@ -1777,6 +1810,42 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fastant" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e825441bfb2d831c47c97d05821552db8832479f44c571b97fededbf0099c07" +dependencies = [ + "small_ctor", + "web-time", +] + +[[package]] +name = "fastrace" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcef89a7c5b37f7c13551af01f509cbd5d32a8644c27423623639eb923cc2973" +dependencies = [ + "fastant", + "fastrace-macro", + "parking_lot", + "pin-project", + "rand 0.10.2", + "rtrb", + "serde", +] + +[[package]] +name = "fastrace-macro" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f1fdb97ada2fde7912c9cab29b560d550ccc467ca1f39c952ce4b05f8d152b3" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -1870,6 +1939,134 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "foyer" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a59f42276891c0a4ce683fcda1aa1b4fd1065d68116c264e4bf49b9d318a0ed" +dependencies = [ + "anyhow", + "asyncband", + "equivalent", + "fastrace", + "foyer-common", + "foyer-memory", + "foyer-storage", + "foyer-tokio", + "futures-util", + "mixtrics", + "pin-project", + "serde", + "tracing", +] + +[[package]] +name = "foyer-common" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "643b47d510032a01e5af70dca288b0c5ec531646c1a8392e793fb5b0c13bef30" +dependencies = [ + "anyhow", + "bincode", + "bytes", + "cfg-if", + "fastrace", + "foyer-tokio", + "mixtrics", + "parking_lot", + "pin-project", + "serde", + "twox-hash", +] + +[[package]] +name = "foyer-intrusive-collections" +version = "0.10.0-dev" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4fee46bea69e0596130e3210e65d3424e0ac1e6df3bde6636304bdf1ca4a3b" +dependencies = [ + "memoffset", +] + +[[package]] +name = "foyer-memory" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae51f5089f3d9025ae77f17ea66d2489ac0f82fbb1d91462807bea174d486d82" +dependencies = [ + "anyhow", + "asyncband", + "bitflags 2.13.0", + "datasketches", + "equivalent", + "fastrace", + "foyer-common", + "foyer-intrusive-collections", + "foyer-tokio", + "futures-util", + "hashbrown 0.17.1", + "itertools", + "mixtrics", + "parking_lot", + "paste", + "pin-project", + "serde", + "tracing", +] + +[[package]] +name = "foyer-storage" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "118192f532ba013f0cdc607efc22324b9ed855baed185608af0daa986e835c6b" +dependencies = [ + "allocator-api2", + "anyhow", + "asyncband", + "bytes", + "core_affinity", + "equivalent", + "fastant", + "fastrace", + "foyer-common", + "foyer-memory", + "foyer-tokio", + "fs4", + "futures-core", + "futures-util", + "hashbrown 0.17.1", + "io-uring", + "itertools", + "libc", + "lz4", + "parking_lot", + "pin-project", + "rand 0.10.2", + "serde", + "tracing", + "twox-hash", + "zstd", +] + +[[package]] +name = "foyer-tokio" +version = "0.22.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6741d1133dfaab64d3f8a9290bbfed3685084add28f8b6ee7a6264aa4dc26918" +dependencies = [ + "tokio", +] + +[[package]] +name = "fs4" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" +dependencies = [ + "rustix", + "windows-sys 0.59.0", +] + [[package]] name = "fs_extra" version = "1.3.0" @@ -2682,6 +2879,17 @@ dependencies = [ "rustversion", ] +[[package]] +name = "io-uring" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" +dependencies = [ + "bitflags 2.13.0", + "cfg-if", + "libc", +] + [[package]] name = "ipconfig" version = "0.3.4" @@ -2710,6 +2918,15 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -3154,6 +3371,25 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "lz4" +version = "1.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a20b523e860d03443e98350ceaac5e71c6ba89aea7d960769ec3ce37f4de5af4" +dependencies = [ + "lz4-sys", +] + +[[package]] +name = "lz4-sys" +version = "1.11.1+lz4-1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bd8c0d6c6ed0cd30b3652886bb8711dc4bb01d637a68105a3d5158039b418e6" +dependencies = [ + "cc", + "libc", +] + [[package]] name = "matchit" version = "0.8.4" @@ -3228,6 +3464,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "mixtrics" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd94ebec15e61a36cd63b1e8816c83434e42926962cd21ee6e4db898d4d4f05" +dependencies = [ + "itertools", + "parking_lot", +] + [[package]] name = "mock_instant" version = "0.6.1" @@ -3614,6 +3860,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "pem" version = "3.0.6" @@ -4457,6 +4709,12 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rtrb" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "342e1478a6e1c839e7405033eabfdc954d4d5dabd39f34e83420a43a95acfb04" + [[package]] name = "rust_decimal" version = "1.42.1" @@ -5049,6 +5307,12 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "small_ctor" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88414a5ca1f85d82cc34471e975f0f74f6aa54c40f062efa42c0080e7f763f81" + [[package]] name = "smallvec" version = "1.15.2" @@ -5572,6 +5836,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + [[package]] name = "typemap-ors" version = "1.0.0" @@ -5814,6 +6084,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-root-certs" version = "1.0.8" diff --git a/Cargo.toml b/Cargo.toml index 986b6a6..8c50d14 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "aralez" -version = "0.95.2" +version = "0.95.4" edition = "2024" license = "Apache-2.0" description = "Reverse proxy built on top of Cloudflare's Pingora" @@ -73,3 +73,6 @@ hickory-resolver = { version = "0.26", features = ["tokio"] } aws-sdk-route53 = "1.127.0" aws-config = { version = "1.12.0", features = ["behavior-version-latest"] } redis = { version = "1.7.1", features = ["tokio-comp", "connection-manager"] } +#foyer = "0.22.6" +foyer = { version = "0.22.6", features = ["serde", "tracing"] } + diff --git a/README.md b/README.md index 9b1ee7b..0c1419f 100644 --- a/README.md +++ b/README.md @@ -60,42 +60,48 @@ Built on Rust, on top of **Cloudflare’s Pingora engine**, **Aralez** delivers ### `main.yaml` -| Key | Example Value | Description | -|----------------------------------|-------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| **threads** | `12` | Number of running daemon threads. Optional, defaults to 1 | -| **runuser** | `aralez` | Optional. Username for running aralez after dropping root privileges (requires launch as root) | -| **rungroup** | `aralez` | Optional. Group for running aralez after dropping root privileges (requires launch as root) | -| **daemon** | `false` | Run in background (boolean) | -| **upstream_keepalive_pool_size** | `500` | Pool size for upstream keepalive connections | -| **pid_file** | `/tmp/aralez.pid` | Path to PID file | -| **upgrade_sock** | `/tmp/aralez.sock` | Path to socket file | -| **config_address** | `0.0.0.0:3000` | HTTP API address for pushing upstreams.yaml from remote location | -| **proxy_tls_grade** | `high, medium, unsafe` | Grade of TLS ciphers. `high` matches Qualys SSL Labs A+ (defaults to `medium`) | -| **proxy_address_http** | `0.0.0.0:6193` | Aralez HTTP bind address | -| **proxy_address_tls** | `0.0.0.0:6194` | Aralez HTTPS bind address (Optional) | -| **proxy_configs** | `/etc/aralez/` | Direcotry containing configuration files, must be writeable by user `aralez` | -| **upstreams_conf** | `/etc/aralez/upstreams.yaml` | Location of the upstreams file | -| **access_log** | `access` | Configure access logging. Values: `access, error` | -| **log_level** | `info` | Log level: `info`, `warn`, `error`, `debug`, `trace`, `off` | -| **log_file** | `/tmp/aralez.log, 20, 5, compress` | Optional, the location of log file, file size in megabytes, number of log files to keep, compress files .valueas are separated by comma. Defaults to None, 100, 5, No | -| **log_pattern** | `{d(%Y-%m-%d %H:%M:%S)} {l} - {m}{n}` | Optional log pattern, defaults to `{d(%Y-%m-%d %H:%M:%S)} {l} - {m}{n}`. See log4rs official [documentation](https://docs.rs/log4rs/latest/log4rs/encode/pattern/struct.PatternEncoderDeserializer.html#configuration) | -| **hc_method** | `HEAD` | Healthcheck method: HEAD, GET, POST (UPPERCASE) | -| **hc_interval** | `2` | Interval for health checks in seconds | -| **file_server_folder** | `/some/local/folder` | Optional. Local folder to serve | -| **file_server_address** | `127.0.0.1:3002` | Optional. Local address for file server | -| **config_api_enabled** | `true` | Enable/disable remote config push capability | -| **cache_size_mb** | `50` | Optional. Enable internal cache with size in megabytes of value. Cache is entirely disabled when this line is commented out. | -| **cache_enabled** | `bool` | Optional. Disabled by default | -| **cache_storage** | `memory, redis://host:port` | Optional Defaults to memory works with Redis, Valkey, Dragonfly (requires redis:// prefix) | -| **cache_item_max_size** | `5` | Optional. Set maximum size for cached items in megabytes. Defaults to 0 , no max size. | -| **cache_ttl** | `60` | Optional. Set internal cache with size in megabytes of value. Defaults to 50Mb if cache_enabled: true | -| **tcp_keepalive_idle** | `60` | Seconds of inactivity before the kernel starts sending keepalive probes to a downstream client. Defaults to 60 | -| **tcp_keepalive_interval** | `10` | Seconds between individual keepalive probes if the client does not respond. Defaults to 10 | -| **tcp_keepalive_count** | `5` | Number of unanswered probes before the kernel declares the connection dead and closes it. Defaults to 5 | -| **cluster_member** | `master, worker` | Optional. Enables cluster mode, Sets node type to master or worker. Disabled by default | -| **worker_nodes** | `http(s)://host:port,http(s)://host:port` | Required is if cluster_member: master. Comma separated list of worker nodes http(s)://host:port | -| **log_structured** | `elasticsearch` | Optional. Enables structured logging and sets backend type. Only elasticsearch et the moment. | -| **acme_dns_provider** | `cloudflare, route53, digitalocean, etc` | Optional. Enable ACME DNS-01 challenge, sets DNS provider. ONly coudflare, route53, digitalocean at the moment. | +| Key | Example Value | Description | +|----------------------------------|---------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------| +| **threads** | `12` | Number of worker threads assigned to proxy operations. Defaults to `1`. | +| **runuser** | `aralez` | Optional. Username to run as after dropping root privileges (requires launch as root). | +| **rungroup** | `aralez` | Optional. Group to run as after dropping root privileges (requires launch as root). | +| **cache** | Optional Block | If omitted entirely, caching is disabled. | +| **cache.storage** | `hybrid` | Storage backend: `"memory"`, `"hybrid"`, or `"redis://host:port"`. Defaults to `"memory"`. | +| **cache.mem_size_mb** | `64` | Optional. Memory cache tier limit in megabytes. Defaults to `64`. | +| **cache.file_size_mb** | `128` | Optional. Disk cache tier limit in megabytes (hybrid mode). Defaults to `512`. | +| **cache.file_path** | `/tmp/cache` | Optional. Directory path for the disk cache tier. Defaults to `/tmp/aralez_cache`. | +| **cache.item_max_size** | `5` | Optional. Maximum allowed size for a single cached item in megabytes. Defaults to `5`. | +| **cache.flush_interval** | `60` | Optional. Interval in seconds to flush memory cache states to disk (hybrid mode). Defaults to `60`. | +| **cache.ttl** | `300` | Optional. Default TTL in seconds used when upstream Cache-Control headers are absent. Defaults to `300`. | +| **upstream_keepalive_pool_size** | `500` | Maximum number of keepalive connections pooled for upstream targets. | +| **pid_file** | `/tmp/aralez.pid` | File system path where the daemon process ID is written. | +| **error_log** | `/tmp/aralez_err.log` | Optional. File path for directing standard error log output when enabled. | +| **upgrade_sock** | `/tmp/aralez.sock` | Unix domain socket path used for zero-downtime binary upgrades and state handoffs. | +| **config_api_enabled** | `true` | Boolean toggle to enable/disable remote runtime configuration push capability. | +| **config_address** | `0.0.0.0:3000` | HTTP API bind address for pushing runtime config updates. | +| **proxy_address_http** | `0.0.0.0:6193` | Primary bind address and port for incoming plain-text HTTP proxy traffic. | +| **proxy_address_tls** | `0.0.0.0:6194` | Optional bind address and port for incoming secure TLS proxy traffic. | +| **proxy_configs** | `/etc/aralez` | Path to directory containing SSL certs and keys in format `{NAME}.crt` and `{NAME}.key`. | +| **upstreams_conf** | `/etc/aralez/upstreams.yaml` | File system path pointing to upstream service routing definitions. | +| **proxy_tls_grade** | `high` | Security grade of TLS cipher suite (`high`, `medium`, `unsafe`). `high` matches Qualys SSL Labs A+. | +| **file_server_folder** | `/opt/public` | Optional. Local file system directory to serve statically. | +| **file_server_address** | `0.0.0.0:3002` | Optional. Local bind address for static file server. | +| **log_level** | `info` | Global logging verbosity threshold (`info`, `warn`, `error`, `debug`, `trace`, `off`). | +| **access_log** | `all` | Access logging mode (`all`, `error`). Omit/comment out to disable. | +| **log_pattern** | `{d(%Y-%m-%d %H:%M:%S)} {h({l})} - {t} - {m} {n}` | Optional custom log pattern. Defaults to `{d(%Y-%m-%d %H:%M:%S)} {l} - {m}{n}`. | +| **log_file** | `/tmp/aralez.log, 20, 5, compress` | Optional file logging config: path, max size (MB), rotated files to keep, compression. | +| **log_structured** | `elasticsearch` | Optional structured logging sink target (e.g., `elasticsearch`). | +| **acme_dns_provider** | `cloudflare` | DNS provider API integration for automated ACME DNS-01 challenges (`cloudflare`, `route53`, `digitalocean`). | +| **hc_method** | `HEAD` | HTTP health check method verb (`HEAD`, `GET`, `POST` in UPPERCASE). | +| **hc_interval** | `5` | Time interval in seconds between periodic upstream health checks. | +| **cluster_member** | `master` | Optional. Operational role in multi-node cluster mode (`master`, `worker`). | +| **worker_nodes** | `http://127.0.0.1:8000, http://127.0.0.1:4000` | Required if `cluster_member: master`. Comma-separated worker management endpoints. | +| **tcp** | Optional Block | Optional advanced Linux TCP socket parameters. Do not alter unless tuned for specific network environments. Values shown act as operational defaults. | +| **tcp.tcp_keepalive_idle** | `30` | Seconds of socket inactivity before sending TCP keepalive probes. Defaults to `30`. | +| **tcp.tcp_keepalive_interval** | `10` | Seconds between individual keepalive probes if no response. Defaults to `10`. | +| **tcp.tcp_keepalive_count** | `5` | Maximum unanswered probes before declaring connection dead. Defaults to `5`. | +| **tcp.so_reuseport** | `true` | Enables `SO_REUSEPORT` for multi-worker connection distribution without lock contention. Defaults to `true`. | +| **tcp.tcp_fastopen** | `4096` | Enables TCP Fast Open backlog queue size. Set to `0` if unsupported by host kernel/container. Defaults to `4096`. | --- diff --git a/etc/main.yaml b/etc/main.yaml index 4aab987..05ca375 100644 --- a/etc/main.yaml +++ b/etc/main.yaml @@ -1,35 +1,41 @@ -# Main configuration file, applied on startup -threads: 12 # Number of daemon threads default setting -runuser: aralez # Username for running aralez after dropping root privileges, requires program to start as root -rungroup: aralez # Group for running aralez after dropping root privileges, requires program to start as root -upstream_keepalive_pool_size: 500 # Pool size for upstream keepalive connections -pid_file: /tmp/aralez.pid # Path to PID file -#error_log: /tmp/aralez_err.log # Path to error log -upgrade_sock: /tmp/aralez.sock # Path to socket file -cache_enabled: true # Optional. Disabled by default -cache_storage: memory # memory | redis://host:port . Optional Defaults to memory works with Redis, Valkey, Dragonfly (requires redis:// prefix) -cache_size_mb: 50 # Optional. Set internal cache with size in megabytes of value. Defaults to 50Mb if cache_enabled: true -cache_ttl: 60 # Optional. Set Default TTL in seconds for cached items, works if cache control headers are not set via upstream. Defaults to 60 if cache_enabled: true -cache_item_max_size: 5 # Optional. Set maximum size for cached items in megabytes. Defaults to 0 , no max size. -config_api_enabled: true # Boolean to enable/disable remote config push capability. -config_address: 127.0.0.1:3000 # HTTP API address for pushing upstreams.yaml from remote location -proxy_address_http: 0.0.0.0:80 # Proxy HTTP bind address -proxy_address_tls: 0.0.0.0:443 # Optional, Proxy TLS bind address -proxy_configs: /opt/aralez/etc # Mandatory if proxy_address_tls set, should contain a certificate and key files strictly in a format {NAME}.crt, {NAME}.key. -proxy_tls_grade: high # Grade of TLS suite for proxy (high, medium, unsafe), matching grades of Qualys SSL Labs -upstreams_conf: /opt/aralez/etc/upstreams.yaml # the location of upstreams file -file_server_folder: /opt/aralez/public # Optional, local folder to serve -file_server_address: 127.0.0.1:3002 # Optional, Local address for file server. Can set as upstream for public access. -log_level: info # info, warn, error, debug, trace, off -log_file: /tmp/aralez.log, 20, 5, compress # Optional, the location of log file, file size in megabytes, number of log files to keep, compress files .valueas are separated by comma. -log_pattern: "{d(%Y-%m-%d %H:%M:%S)} {h({l})} {t} - {m} {n}" # Optional log pattern, defaults to "{d(%Y-%m-%d %H:%M:%S)} {l} - {m}{n}" -access_log: error # all, error, (Off by default) -hc_method: HEAD # Healthcheck method (HEAD, GET, POST are supported) UPPERCASE -hc_interval: 2 #Interval for health checks in seconds -tcp_keepalive_idle: 60 # Seconds of inactivity before the kernel starts sending keepalive probes to a downstream client -tcp_keepalive_interval: 10 # Seconds between individual keepalive probes if the client does not respond -tcp_keepalive_count: 5 # Number of unanswered probes before the kernel declares the connection dead and closes it -#cluster_member: master | worker Optional. Enables cluster mode, Sets node type to master or worker. Disabled by default -#worker_nodes: http://127.0.0.1:8000, http://127.0.0.1:4000 Required is if cluster_member: master. Comma separated list of worker nodes http(s)://host:port -#log_structured: elasticsearch Optional. Enables structured logging and sets backend type. Only elasticsearch et the moment. -#acme_dns_provider: cloudflare Optional. Enable ACME DNS-01 challenge, sets DNS provider. ONly coudflare, route53, digitalocean at the moment. +threads: 12 # Number of daemon worker threads assigned to proxy operations +runuser: aralez # Username used to drop root privileges after binding to low ports; requires the process to start as root +rungroup: aralez # Group used to drop root privileges after binding to low ports; requires the process to start as root +cache: # Optional block. If omitted entirely, caching is disabled. + storage: "hybrid" # Storage backend: "memory", "hybrid", or "redis://host:port" (compatible with Redis, Valkey, Dragonfly). Defaults to "memory". + mem_size_mb: 64 # Optional. Memory cache tier limit in megabytes. Defaults to 64. + file_size_mb: 128 # Optional. Disk cache tier limit in megabytes (hybrid mode). Defaults to 512. + file_path: "/tmp/cache" # Optional. Directory path for the disk cache tier. Defaults to "/tmp/aralez_cache". + item_max_size: 5 # Optional. Maximum allowed size for a single cached item in megabytes. Defaults to 5. + flush_interval: 60 # Optional. Interval in seconds for flushing memory cache states to disk (hybrid mode). Defaults to 60. + ttl: 300 # Optional. Default Time-To-Live (TTL) in seconds used when upstream Cache-Control headers are absent. Defaults to 300. +upstream_keepalive_pool_size: 500 # Maximum number of keepalive connections pooled for upstream targets +pid_file: /tmp/aralez.pid # File system path where the daemon process ID is written +#error_log: /tmp/aralez_err.log # File system path for directing standard error log output when enabled +upgrade_sock: /tmp/aralez.sock # Unix domain socket path used for zero-downtime binary upgrades and state handoffs +config_api_enabled: true # Boolean toggle to enable or disable remote runtime configuration push capabilities +config_address: 0.0.0.0:3000 # HTTP API bind address for remotely pushing upstreams.yaml updates +proxy_address_http: 0.0.0.0:80 # Primary bind address and port for incoming plain-text HTTP proxy traffic +proxy_address_tls: 0.0.0.0:443 # Optional bind address and port for incoming secure TLS proxy traffic +proxy_configs: /etc/aralez # Mandatory if proxy_address_tls is set; directory must contain certificate and key files strictly following the naming format {NAME}.crt and {NAME}.key +upstreams_conf: /etc/aralez/upstreams.yaml # File system path pointing to the upstream service routing definitions +proxy_tls_grade: high # Security grade of the TLS cipher suite (options: high, medium, unsafe), matching Qualys SSL Labs rating tiers +file_server_folder: /opt/public # Optional local file system directory to serve statically +file_server_address: 0.0.0.0:3002 # Optional local bind address for the static file server (can be routed as an upstream for public access) +log_level: info # Global logging verbosity threshold (options: info, warn, error, debug, trace, off) +access_log: all # Access logging mode filter (options: all, error; comment out entirely to disable access logs) +log_pattern: "{d(%Y-%m-%d %H:%M:%S)} {h({l})} - {t} - {m} {n}" # Optional custom log message pattern format +#log_file: /tmp/aralez.log, 20, 5, compress # Optional file logging configuration: file path, max file size in megabytes, number of rotated logs to retain, and compression flag (comma-separated). Defaults to stdout if commented. +#log_structured: elasticsearch # Optional structured logging sink target format (e.g., elasticsearch) +acme_dns_provider: cloudflare # DNS provider API integration used for automated ACME Let's Encrypt DNS-01 challenges +hc_method: HEAD # HTTP health check method verb (options: HEAD, GET, POST; must be uppercase) +hc_interval: 5 # Time interval in seconds between periodic upstream health checks +#cluster_member: master # Designates this node's operational role within a multi-node cluster configuration (e.g., master) +#cluster_member: worker # Designates this node's operational role within a multi-node cluster configuration (e.g., worker) +#worker_nodes: http://127.0.0.1:8000, http://127.0.0.1:4000 # Comma-separated list of peer worker node management endpoints for cluster synchronization +tcp: # Optional advanced Linux TCP socket parameters. Do not alter unless tuned for specific network environments. Values shown act as operational defaults. + tcp_keepalive_idle: 30 # Seconds of socket inactivity before the kernel initiates TCP keepalive probes to a downstream client + tcp_keepalive_interval: 10 # Seconds of delay between individual keepalive probes if the client fails to respond + tcp_keepalive_count: 5 # Maximum number of unanswered probes before the kernel terminates the dead connection + so_reuseport: true # Enables SO_REUSEPORT to allow multiple worker threads to bind the port, evenly distributing connection queues without lock contention + tcp_fastopen: 4096 # Enables TCP Fast Open with the specified SYN-backlog queue size (set to 0 if unsupported by the host kernel or container) diff --git a/src/cache/hybrid.rs b/src/cache/hybrid.rs new file mode 100644 index 0000000..6a37c7f --- /dev/null +++ b/src/cache/hybrid.rs @@ -0,0 +1,243 @@ +use async_trait::async_trait; +use bytes::Bytes; +use foyer::{BlockEngineConfig, DeviceBuilder, FsDeviceBuilder, HybridCache, HybridCacheBuilder, HybridCachePolicy, PsyncIoEngineConfig, RecoverMode}; +use log::info; +use pingora::Result; +use pingora_cache::storage::{HandleHit, HandleMiss, HitHandler, MissFinishType, MissHandler, Storage}; +use pingora_cache::trace::SpanHandle; +use pingora_cache::{CacheKey, CacheMeta, PurgeOutcome, PurgeTarget, PurgeType}; +use serde::{Deserialize, Serialize}; +use std::any::Any; +use std::hash::{Hash, Hasher}; +use std::sync::OnceLock; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub static HYBRID_CACHE: OnceLock> = OnceLock::new(); + +#[derive(Serialize, Deserialize, Clone)] +pub struct CacheItem { + pub expires_at: u64, + pub internal_bytes: Vec, + pub header_bytes: Vec, + pub body_bytes: Vec, +} + +impl CacheItem { + pub fn new(internal_bytes: Vec, header_bytes: Vec, body_bytes: Vec, ttl_seconds: u64) -> Self { + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); + Self { + expires_at: now + ttl_seconds, + internal_bytes, + header_bytes, + body_bytes, + } + } + + pub fn is_expired(&self) -> bool { + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); + now > self.expires_at + } +} + +pub async fn foy_init(m: usize, f: usize, dir: &str, flush: u64) -> anyhow::Result<()> { + let memsize = m * 1024 * 1024; + let filesize = f * 1024 * 1024; + + let device = FsDeviceBuilder::new(dir).with_capacity(filesize).build()?; + let cache: HybridCache = HybridCacheBuilder::new() + .with_policy(HybridCachePolicy::WriteOnEviction) + .memory(memsize) + .storage() + .with_io_engine_config(PsyncIoEngineConfig::new()) + .with_engine_config(BlockEngineConfig::new(device)) + .with_recover_mode(RecoverMode::Strict) + .build() + .await?; + + let _ = HYBRID_CACHE.set(cache); + + tokio::spawn(async move { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(flush)); + loop { + tokio::select! { + _ = interval.tick() => { + if let Some(cache) = HYBRID_CACHE.get() { + info!("Flushing {} cache entries to disk", cache.memory().entries()); + let _ = cache.flush_if(|_, _| true).await; + } + } + } + } + }); + + info!("Hybrid cache initialized with memory: {}mb, path: {}, size: {}mb", m, dir, f); + Ok(()) +} + +#[derive(Clone)] +pub struct FoyerCache { + pub ttl: u64, +} + +pub struct FoyerHitHandler { + body: Option, +} + +pub struct FoyerMissHandler { + key: u64, + internal_bytes: Vec, + header_bytes: Vec, + body_buffer: Vec, + ttl: u64, +} + +impl FoyerCache { + pub fn new(ttl: u64) -> Self { + Self { ttl } + } + + fn hash_key(key: &CacheKey) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + + if let Some(s) = key.primary_key_str() { + s.hash(&mut hasher); + } else { + key.primary_key().hash(&mut hasher); + } + hasher.finish() + } +} + +#[async_trait] +impl HandleHit for FoyerHitHandler { + async fn read_body(&mut self) -> Result> { + Ok(self.body.take()) + } + + async fn finish(self: Box, _storage: &'static (dyn Storage + Sync), _key: &CacheKey, _trace: &SpanHandle) -> Result<()> { + Ok(()) + } + + fn can_seek(&self) -> bool { + false + } + + fn seek(&mut self, _start: usize, _end: Option) -> Result<()> { + Ok(()) + } + + fn should_count_access(&self) -> bool { + true + } + + fn get_eviction_weight(&self) -> usize { + self.body.as_ref().map(|b| b.len()).unwrap_or(0) + } + + fn entry_id(&self) -> Option { + None + } + + fn as_any(&self) -> &(dyn Any + Send + Sync) { + self + } + + fn as_any_mut(&mut self) -> &mut (dyn Any + Send + Sync) { + self + } +} + +#[async_trait] +impl HandleMiss for FoyerMissHandler { + async fn write_body(&mut self, data: Bytes, _eof: bool) -> Result<()> { + self.body_buffer.extend_from_slice(&data); + Ok(()) + } + + async fn finish(self: Box) -> Result { + let len = self.body_buffer.len(); + let item = CacheItem::new(self.internal_bytes, self.header_bytes, self.body_buffer, self.ttl); + if let Some(cache) = HYBRID_CACHE.get() { + cache.insert(self.key, item); + } + Ok(MissFinishType::Appended(len, None)) + } + + fn entry_id(&self) -> Option { + None + } +} + +#[async_trait] +impl Storage for FoyerCache { + async fn lookup(&'static self, key: &CacheKey, _trace: &SpanHandle) -> Result> { + let k = Self::hash_key(key); + + if let Some(cache) = HYBRID_CACHE.get() { + if let Ok(Some(entry)) = cache.get(&k).await { + let item = entry.value(); + if item.is_expired() { + return Ok(None); + } + match CacheMeta::deserialize(&item.internal_bytes, &item.header_bytes) { + Ok(meta) => { + let handler: HitHandler = Box::new(FoyerHitHandler { + body: Some(Bytes::from(item.body_bytes.clone())), + }); + return Ok(Some((meta, handler))); + } + Err(_) => { + return Ok(None); + } + } + } + } + Ok(None) + } + + async fn get_miss_handler(&'static self, key: &CacheKey, meta: &CacheMeta, _trace: &SpanHandle) -> Result { + let k = Self::hash_key(key); + let (internal_bytes, header_bytes) = meta.serialize()?; + + Ok(Box::new(FoyerMissHandler { + key: k, + internal_bytes, + header_bytes, + body_buffer: Vec::with_capacity(4096), + ttl: self.ttl, + })) + } + + async fn purge(&'static self, _target: PurgeTarget<'_>, _purge_type: PurgeType, _trace: &SpanHandle) -> Result { + Ok(PurgeOutcome::NotFound) + } + + async fn update_meta(&'static self, key: &CacheKey, meta: &CacheMeta, _trace: &SpanHandle) -> Result { + let k = Self::hash_key(key); + if let Some(cache) = HYBRID_CACHE.get() { + // Fix: Match the Result containing an Option just like lookup + if let Ok(Some(entry)) = cache.get(&k).await { + let existing = entry.value().clone(); + if let Ok((internal_bytes, header_bytes)) = meta.serialize() { + let updated = CacheItem { + expires_at: existing.expires_at, + internal_bytes, + header_bytes, + body_bytes: existing.body_bytes, + }; + cache.insert(k, updated); + return Ok(true); + } + } + } + Ok(false) + } + + fn support_streaming_partial_write(&self) -> bool { + false + } + + fn as_any(&self) -> &(dyn Any + Send + Sync) { + self + } +} diff --git a/src/cache/mod.rs b/src/cache/mod.rs index c7372e0..6ebcd8e 100644 --- a/src/cache/mod.rs +++ b/src/cache/mod.rs @@ -1,2 +1,3 @@ +pub mod hybrid; pub mod redis; pub mod types; diff --git a/src/cache/types.rs b/src/cache/types.rs index 6b98b41..ddee7df 100644 --- a/src/cache/types.rs +++ b/src/cache/types.rs @@ -1,7 +1,8 @@ +use crate::cache::hybrid::{FoyerCache, foy_init}; use crate::cache::redis::RedisCache; use crate::utils::lazylock::{CACHE_TTL, EVICTION}; use crate::utils::types::AppConfig; -use log::{info, warn}; +use log::{error, info, warn}; use pingora_cache::eviction::simple_lru::Manager; use pingora_cache::{MemCache, Storage}; use std::sync::{Arc, OnceLock}; @@ -9,34 +10,95 @@ use std::sync::{Arc, OnceLock}; pub static GLOBAL_STORAGE: OnceLock> = OnceLock::new(); pub async fn init_cache(config: Arc) { - let cache_storage = config.cache_storage.clone().unwrap_or_else(|| { - info!("No cache_storage configured, defaulting to memory"); - "memory".to_string() - }); - let cache_type = cache_storage.splitn(2, ':').next().unwrap_or("memory"); - let ttl = config.cache_ttl.unwrap_or(60); + if let Some(cache) = &config.cache { + let storage = cache.storage.clone().unwrap_or_else(|| { + info!("No cache_storage configured, defaulting to memory"); + "memory".to_string() + }); + let cache_type = storage.splitn(2, ':').next().unwrap_or("memory"); + let ttl = cache.ttl.unwrap_or(60); - match cache_type { - "memory" => { - CACHE_TTL.set(ttl).ok(); - if let Some(size) = config.cache_size_mb { + match cache_type { + "memory" => { + CACHE_TTL.set(ttl).ok(); + let size = cache.mem_size_mb.unwrap_or(64); let cache_size = size * 1024 * 1024; let manager = Manager::new(cache_size); let _ = EVICTION.set(manager); + GLOBAL_STORAGE.set(Box::new(MemCache::new())).ok(); + info!("Cache initialized successfully. Storage: {}", storage); } - GLOBAL_STORAGE.set(Box::new(MemCache::new())).ok(); - info!("Cache initialized successfully. Storage: {}", cache_storage); - } - "redis" => match RedisCache::new(&cache_storage, ttl).await { - Ok(cache) => { - CACHE_TTL.set(ttl).ok(); - GLOBAL_STORAGE.set(Box::new(cache)).ok(); - info!("Cache initialized successfully. Storage: {}", cache_storage); + "redis" => match RedisCache::new(&storage, ttl).await { + Ok(cache) => { + CACHE_TTL.set(ttl).ok(); + GLOBAL_STORAGE.set(Box::new(cache)).ok(); + info!("Cache initialized successfully. Storage: {}", storage); + } + Err(e) => log::error!("Cache storage initialization failed: {}", e), + }, + "hybrid" => { + if let Some(cache) = config.cache.clone() { + let mem_size = cache.mem_size_mb.unwrap_or(64); + let fs_size = cache.file_size_mb.unwrap_or(512); + let flush = cache.flush_interval.unwrap_or(60); + let folder = cache.file_path.clone().unwrap_or("/tmp/aralez_cache".to_string()); + let _ = foy_init(mem_size, fs_size, folder.as_str(), flush).await; + CACHE_TTL.set(ttl).ok(); + match GLOBAL_STORAGE.set(Box::new(FoyerCache::new(ttl))) { + Ok(_) => {} + Err(_) => error!("CRITICAL: GLOBAL_STORAGE was already set before hybrid init!"), + } + }; + } + _ => { + warn!("Unsupported storage, disabling caching: {}", storage); } - Err(e) => log::error!("Cache storage initialization failed: {}", e), - }, - _ => { - warn!("Unsupported storage, disabling caching: {}", cache_storage); } + } else { + info!("Cache engine is not configured, disabling."); } + // ----------------------------------------------------------------------------------------------------- // + // let cache_storage = config.cache_storage.clone().unwrap_or_else(|| { + // info!("No cache_storage configured, defaulting to memory"); + // "memory".to_string() + // }); + // let cache_type = cache_storage.splitn(2, ':').next().unwrap_or("memory"); + // let ttl = config.cache_ttl.unwrap_or(60); + + // match cache_type { + // "memory" => { + // CACHE_TTL.set(ttl).ok(); + // let size = config.cache_size_mb.unwrap_or(64); + // let cache_size = size * 1024 * 1024; + // let manager = Manager::new(cache_size); + // let _ = EVICTION.set(manager); + // GLOBAL_STORAGE.set(Box::new(MemCache::new())).ok(); + // info!("Cache initialized successfully. Storage: {}", cache_storage); + // } + // "redis" => match RedisCache::new(&cache_storage, ttl).await { + // Ok(cache) => { + // CACHE_TTL.set(ttl).ok(); + // GLOBAL_STORAGE.set(Box::new(cache)).ok(); + // info!("Cache initialized successfully. Storage: {}", cache_storage); + // } + // Err(e) => log::error!("Cache storage initialization failed: {}", e), + // }, + // "hybrid" => { + // if let Some(cache) = config.cache.clone() { + // let mem_size = cache.mem_size_mb.unwrap_or(64); + // let fs_size = cache.file_size_mb.unwrap_or(512); + // let flush = cache.flush_interval.unwrap_or(60); + // let folder = cache.file_path.clone().unwrap_or("/tmp/aralez_cache".to_string()); + // let _ = foy_init(mem_size, fs_size, folder.as_str(), flush).await; + // CACHE_TTL.set(ttl).ok(); + // match GLOBAL_STORAGE.set(Box::new(FoyerCache::new(ttl))) { + // Ok(_) => {} + // Err(_) => error!("CRITICAL: GLOBAL_STORAGE was already set before hybrid init!"), + // } + // }; + // } + // _ => { + // warn!("Unsupported storage, disabling caching: {}", cache_storage); + // } + // } } diff --git a/src/core/start.rs b/src/core/start.rs index 1a00e32..7b14b98 100644 --- a/src/core/start.rs +++ b/src/core/start.rs @@ -3,14 +3,12 @@ use crate::tls::grades; use crate::tls::load; use crate::tls::load::CertificateConfig; use crate::utils::folder_watch; -use crate::utils::lazylock::{CACHE_TTL, EVICTION}; use crate::utils::tools::*; use crate::utils::types::Extraparams; use arc_swap::ArcSwap; use dashmap::DashMap; use log::info; use pingora::tls::ssl::{SslAlert, SslRef}; -use pingora_cache::eviction::simple_lru::Manager; use pingora_core::listeners::TcpSocketOptions; use pingora_core::listeners::tls::TlsSettings; use pingora_core::prelude::{Opt, background_service}; @@ -35,15 +33,21 @@ pub fn run() { let maincfg = crate::utils::parceyaml::parce_main_config(file.as_str()); let master_server = maincfg.cluster_member.as_deref() == Some("master"); - - let cache_enabled = maincfg.cache_enabled.unwrap_or(false); + let cache_enabled = maincfg.cache.is_some(); // ========================================================================== // - CACHE_TTL.set(maincfg.cache_ttl.unwrap_or(60)).die("Failed to set cache TTL"); - if cache_enabled { - let cache_size = maincfg.cache_size_mb.unwrap_or(50); - let _ = EVICTION.set(Manager::new(cache_size * 1024 * 1024)); - } + // let mut cache_enabled = false; + // if let Some(cache) = maincfg.cache.clone() { + // CACHE_TTL.set(cache.ttl.unwrap_or(60)).die("Failed to set cache TTL"); + // let cache_size = cache.mem_size_mb.unwrap_or(64); + // let _ = EVICTION.set(Manager::new(cache_size * 1024 * 1024)); + // cache_enabled = true; + // } + // CACHE_TTL.set(maincfg.cache_ttl.unwrap_or(60)).die("Failed to set cache TTL"); + // if cache_enabled { + // let cache_size = maincfg.cache_size_mb.unwrap_or(50); + // let _ = EVICTION.set(Manager::new(cache_size * 1024 * 1024)); + // } // ========================================================================== // let mut server = Server::new(parameters).die("Failed to start the server:"); @@ -86,26 +90,20 @@ pub fn run() { let bind_address_tls = cfg.proxy_address_tls.clone(); let mut proxy = pingora_proxy::http_proxy_service(&server.configuration, lb.clone()); - check_priv(bind_address_http.as_str()); - let mut tcp_options: Option = None; - if let Some(idle) = cfg.tcp_keepalive_idle { + let tcp_options = cfg.tcp.as_ref().map(|tcp| { let mut to = TcpSocketOptions::default(); to.tcp_keepalive = Some(TcpKeepalive { - idle: Duration::from_secs(idle), - interval: Duration::from_secs(cfg.tcp_keepalive_interval.unwrap_or(10)), + idle: Duration::from_secs(tcp.tcp_keepalive_idle.unwrap_or(30)), + interval: Duration::from_secs(tcp.tcp_keepalive_interval.unwrap_or(10)), user_timeout: Default::default(), - count: cfg.tcp_keepalive_count.unwrap_or(5usize), + count: tcp.tcp_keepalive_count.unwrap_or(5usize), }); - tcp_options = Some(to); - info!( - "Applying kernel tcp_keepalive parameters: idle {}, interval {}, count {}", - idle, - cfg.tcp_keepalive_interval.unwrap_or(60), - cfg.tcp_keepalive_count.unwrap_or(5), - ); - } + to.so_reuseport = Some(tcp.so_reuseport.unwrap_or(true)); + to.tcp_fastopen = tcp.tcp_fastopen.or(Some(4096)); + to + }); if let Some(bind_address_tls) = bind_address_tls { check_priv(bind_address_tls.as_str()); @@ -166,11 +164,18 @@ pub fn run() { if let Err(e) = write_pid_file(pf.as_str()) { panic!("Failed to write PID file: {} : {}", pf, e); } + let mut signals = Signals::new([SIGINT, SIGTERM, SIGQUIT]).die("Failed to create signals"); if let Some(sig) = signals.forever().next() { match sig { - SIGINT => info!("SIGINT received! Exiting..."), - SIGTERM => info!("SIGTERM received! Exiting..."), + SIGINT => { + info!("SIGINT received! Exiting..."); + thread::sleep(Duration::from_secs(5)) + } + SIGTERM => { + info!("SIGTERM received! Exiting..."); + thread::sleep(Duration::from_secs(5)) + } SIGQUIT => { thread::sleep(Duration::from_secs(300)); info!("SIGQUIT received! Exiting...") diff --git a/src/core/webserver.rs b/src/core/webserver.rs index 05ce37a..84ea40f 100644 --- a/src/core/webserver.rs +++ b/src/core/webserver.rs @@ -97,7 +97,7 @@ pub async fn run_server(config: &APIUpstreamProvider, mut to_return: mpsc::Sende std::thread::spawn(move || { let mut signals = Signals::new([SIGQUIT]).die("Can't initialize OS SIGNALS"); if let Some(sig) = signals.forever().next() { - tx.blocking_send(sig).die("Can;t send signal to main thread"); + tx.blocking_send(sig).die("Can't send signal to main thread"); } }); rx.recv().await; diff --git a/src/utils/metrics.rs b/src/utils/metrics.rs index 9392dbe..9ffab20 100644 --- a/src/utils/metrics.rs +++ b/src/utils/metrics.rs @@ -39,6 +39,10 @@ pub static CACHE_EVICTED_BYTES: LazyLock = pub static CACHE_EVICTED_ITEMS: LazyLock = LazyLock::new(|| register_int_gauge!("aralez_cache_evicted_items_total", "Total cache items evicted").die("Failed to register CACHE_EVICTED_ITEMS metric")); + +pub static CACHE_PHASE: LazyLock = + LazyLock::new(|| register_int_counter_vec!("aralez_cache_status", "Phases of cached responses", &["phase"]).die("Failed to register CACHE_PHASE metric")); + pub static RESPONSE_CODES: LazyLock = LazyLock::new(|| register_int_counter_vec!("aralez_responses_total", "Responses grouped by status code", &["status"]).die("Failed to register RESPONSE_CODES metric")); @@ -55,9 +59,6 @@ pub static REQUESTS_BY_METHOD: LazyLock = LazyLock::new(|| { register_int_counter_vec!("aralez_requests_by_method_total", "Number of requests by HTTP method", &["method"]).die("Failed to register REQUESTS_BY_METHOD metric") }); -pub static CACHE_PHASE: LazyLock = - LazyLock::new(|| register_int_counter_vec!("aralez_cache_status", "Phases of cached responses", &["phase"]).die("Failed to register CACHE_PHASE metric")); - pub static REQUESTS_BY_UPSTREAM: LazyLock = LazyLock::new(|| { register_int_counter_vec!("aralez_requests_by_upstream", "Number of requests by UPSTREAM server", &["upstream"]).die("Failed to register REQUESTS_BY_UPSTREAM metric") }); diff --git a/src/utils/parceyaml.rs b/src/utils/parceyaml.rs index b630f62..274bbe7 100644 --- a/src/utils/parceyaml.rs +++ b/src/utils/parceyaml.rs @@ -281,8 +281,11 @@ pub fn parce_main_config(path: &str) -> AppConfig { } else if let Ok(jwt_key) = env::var("JWT_KEY") { cfo.master_key = Some(jwt_key); }; - if let Some(cs) = cfo.cache_item_max_size { - cfo.cache_item_max_size = Some(cs * 1024 * 1024); + + if let Some(cache) = &cfo.cache { + cfo.cache_item_max_size = Some(cache.item_max_size.unwrap_or(5) * 1024 * 1024); + } else { + cfo.cache_item_max_size = Some(5 * 1024 * 1024); } // log_builder(&cfo, &cfo.log_file); cfo.hc_method = cfo.hc_method.to_uppercase(); diff --git a/src/utils/types.rs b/src/utils/types.rs index 5c5051b..e5cf59c 100644 --- a/src/utils/types.rs +++ b/src/utils/types.rs @@ -106,26 +106,48 @@ pub struct Configuration { pub extraparams: Extraparams, } +#[derive(Debug, Default, Serialize, Deserialize, Clone)] +pub struct CacheConfig { + pub storage: Option, + pub mem_size_mb: Option, + pub file_size_mb: Option, + pub file_path: Option, + pub item_max_size: Option, + pub flush_interval: Option, + pub ttl: Option, +} +#[derive(Debug, Default, Serialize, Deserialize, Clone)] +pub struct LinuxTCP { + pub tcp_keepalive_idle: Option, + pub tcp_keepalive_interval: Option, + pub tcp_fastopen: Option, + pub tcp_keepalive_count: Option, + pub so_reuseport: Option, +} #[derive(Debug, Default, Serialize, Deserialize)] pub struct AppConfig { pub hc_interval: u16, pub hc_method: String, pub upstreams_conf: String, pub log_level: String, - pub cache_enabled: Option, - pub cache_storage: Option, - pub cache_size_mb: Option, + pub cache: Option, + // pub cache_enabled: Option, + // pub cache_storage: Option, + // pub cache_size_mb: Option, + // pub cache_file_size: Option, + // pub cache_file_location: Option, pub cache_item_max_size: Option, - pub cache_ttl: Option, + // pub cache_flush_interval: Option, + // pub cache_ttl: Option, pub access_log: Option, pub pid_file: Option, pub master_key: Option, pub config_address: String, pub proxy_address_http: String, pub config_api_enabled: bool, - pub config_tls_address: Option, - pub config_tls_certificate: Option, - pub config_tls_key_file: Option, + // pub config_tls_address: Option, + // pub config_tls_certificate: Option, + // pub config_tls_key_file: Option, pub proxy_address_tls: Option, pub proxy_port_tls: Option, pub proxy_port: Option, @@ -140,11 +162,12 @@ pub struct AppConfig { pub log_pattern: Option, pub log_structured: Option, pub acme_dns_provider: Option, - pub tcp_keepalive_idle: Option, - pub tcp_keepalive_interval: Option, - pub tcp_keepalive_count: Option, pub cluster_member: Option, pub worker_nodes: Option, + // pub tcp_keepalive_idle: Option, + // pub tcp_keepalive_interval: Option, + // pub tcp_keepalive_count: Option, + pub tcp: Option, } #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize)]