Added TiKV support as a cache storage

This commit is contained in:
Ara Sadoyan
2026-10-31 12:27:55 +01:00
parent 6beb5fe234
commit d6936a2a0e
6 changed files with 661 additions and 71 deletions
Generated
+396 -24
View File
@@ -138,7 +138,7 @@ dependencies = [
"async-trait",
"aws-config",
"aws-sdk-route53",
"axum",
"axum 0.8.9",
"base16ct 1.0.0",
"base64 0.23.1",
"bytes",
@@ -171,19 +171,20 @@ dependencies = [
"pingora-limits",
"pingora-proxy",
"privdrop",
"prometheus",
"prometheus 0.14.0",
"rand 0.10.2",
"rcgen",
"redis",
"reqwest",
"rustls 0.23.41",
"rustls-pemfile",
"rustls-pemfile 2.2.0",
"sd-notify",
"serde",
"serde_json",
"sha2 0.11.0",
"signal-hook",
"subtle",
"tikv-client",
"tokio",
"tokio-native-tls",
"tower-http 0.7.1",
@@ -304,6 +305,17 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "async-recursion"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7d78656ba01f1b93024b7c3a0467f1608e4be67d725749fdcd7d2c7678fd7a2"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "async-stream"
version = "0.3.6"
@@ -627,7 +639,7 @@ dependencies = [
"rustls-pki-types",
"tokio",
"tokio-rustls 0.26.4",
"tower",
"tower 0.5.3",
"tracing",
]
@@ -781,13 +793,41 @@ dependencies = [
"tracing",
]
[[package]]
name = "axum"
version = "0.6.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf"
dependencies = [
"async-trait",
"axum-core 0.3.4",
"bitflags 1.3.2",
"bytes",
"futures-util",
"http 0.2.12",
"http-body 0.4.6",
"hyper 0.14.32",
"itoa",
"matchit 0.7.3",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"rustversion",
"serde",
"sync_wrapper 0.1.2",
"tower 0.4.13",
"tower-layer",
"tower-service",
]
[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"axum-core 0.5.6",
"bytes",
"form_urlencoded",
"futures-util",
@@ -797,7 +837,7 @@ dependencies = [
"hyper 1.11.1",
"hyper-util",
"itoa",
"matchit",
"matchit 0.8.4",
"memchr",
"mime",
"percent-encoding",
@@ -806,14 +846,31 @@ dependencies = [
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sync_wrapper",
"sync_wrapper 1.0.2",
"tokio",
"tower",
"tower 0.5.3",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "axum-core"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c"
dependencies = [
"async-trait",
"bytes",
"futures-util",
"http 0.2.12",
"http-body 0.4.6",
"mime",
"rustversion",
"tower-layer",
"tower-service",
]
[[package]]
name = "axum-core"
version = "0.5.6"
@@ -827,7 +884,7 @@ dependencies = [
"http-body-util",
"mime",
"pin-project-lite",
"sync_wrapper",
"sync_wrapper 1.0.2",
"tower-layer",
"tower-service",
"tracing",
@@ -856,6 +913,12 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6"
[[package]]
name = "base64"
version = "0.21.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
[[package]]
name = "base64"
version = "0.22.1"
@@ -1561,6 +1624,17 @@ dependencies = [
"syn 1.0.109",
]
[[package]]
name = "derive-new"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3418329ca0ad70234b9735dc4ceed10af4df60eff9c8e7b06cb5e520d92c3535"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "derive_more"
version = "2.1.1"
@@ -1810,6 +1884,17 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "fail"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3be3c61c59fdc91f5dbc3ea31ee8623122ce80057058be560654c5d410d181a6"
dependencies = [
"lazy_static",
"log",
"rand 0.7.3",
]
[[package]]
name = "fastant"
version = "0.1.11"
@@ -2005,7 +2090,7 @@ dependencies = [
"foyer-tokio",
"futures-util",
"hashbrown 0.17.1",
"itertools",
"itertools 0.15.0",
"mixtrics",
"parking_lot",
"paste",
@@ -2036,7 +2121,7 @@ dependencies = [
"futures-util",
"hashbrown 0.17.1",
"io-uring",
"itertools",
"itertools 0.15.0",
"libc",
"lz4",
"parking_lot",
@@ -2063,7 +2148,7 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4"
dependencies = [
"rustix",
"rustix 1.1.4",
"windows-sys 0.59.0",
]
@@ -2172,6 +2257,17 @@ dependencies = [
"zeroize",
]
[[package]]
name = "getrandom"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce"
dependencies = [
"cfg-if",
"libc",
"wasi 0.9.0+wasi-snapshot-preview1",
]
[[package]]
name = "getrandom"
version = "0.2.17"
@@ -2180,7 +2276,7 @@ checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
"wasi 0.11.1+wasi-snapshot-preview1",
]
[[package]]
@@ -2613,6 +2709,18 @@ dependencies = [
"tower-service",
]
[[package]]
name = "hyper-timeout"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbb958482e8c7be4bc3cf272a766a2b0bf1a6755e7a6ae777f017a31d11b13b1"
dependencies = [
"hyper 0.14.32",
"pin-project-lite",
"tokio",
"tokio-io-timeout",
]
[[package]]
name = "hyper-timeout"
version = "0.5.2"
@@ -2918,6 +3026,15 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.15.0"
@@ -3175,7 +3292,7 @@ dependencies = [
"http-body-util",
"hyper 1.11.1",
"hyper-rustls 0.27.9",
"hyper-timeout",
"hyper-timeout 0.5.2",
"hyper-util",
"jiff",
"jsonpath-rust",
@@ -3191,7 +3308,7 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tokio-util",
"tower",
"tower 0.5.3",
"tower-http 0.6.11",
"tracing",
]
@@ -3296,6 +3413,12 @@ dependencies = [
"libc",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
@@ -3390,6 +3513,12 @@ dependencies = [
"libc",
]
[[package]]
name = "matchit"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"
[[package]]
name = "matchit"
version = "0.8.4"
@@ -3460,7 +3589,7 @@ checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"
dependencies = [
"libc",
"log",
"wasi",
"wasi 0.11.1+wasi-snapshot-preview1",
"windows-sys 0.61.2",
]
@@ -3470,7 +3599,7 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dd94ebec15e61a36cd63b1e8816c83434e42926962cd21ee6e4db898d4d4f05"
dependencies = [
"itertools",
"itertools 0.15.0",
"parking_lot",
]
@@ -4361,6 +4490,47 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "procfs"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "731e0d9356b0c25f16f33b5be79b1c57b562f141ebfcdb0ad8ac2c13a24293b4"
dependencies = [
"bitflags 2.13.0",
"hex",
"lazy_static",
"procfs-core",
"rustix 0.38.44",
]
[[package]]
name = "procfs-core"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d3554923a69f4ce04c4a754260c338f505ce22642d3830e049a399fc2059a29"
dependencies = [
"bitflags 2.13.0",
"hex",
]
[[package]]
name = "prometheus"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d33c28a30771f7f96db69893f78b857f7450d7e0237e9c8fc6427a81bae7ed1"
dependencies = [
"cfg-if",
"fnv",
"lazy_static",
"libc",
"memchr",
"parking_lot",
"procfs",
"protobuf 2.28.0",
"reqwest",
"thiserror 1.0.69",
]
[[package]]
name = "prometheus"
version = "0.14.0"
@@ -4372,10 +4542,39 @@ dependencies = [
"lazy_static",
"memchr",
"parking_lot",
"protobuf",
"protobuf 3.7.2",
"thiserror 2.0.18",
]
[[package]]
name = "prost"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-derive"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1"
dependencies = [
"anyhow",
"itertools 0.10.5",
"proc-macro2",
"quote",
"syn 2.0.118",
]
[[package]]
name = "protobuf"
version = "2.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "106dd99e98437432fed6519dedecfade6a06a73bb7b2a1e019fdd2bee5778d94"
[[package]]
name = "protobuf"
version = "3.7.2"
@@ -4417,6 +4616,19 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"
dependencies = [
"getrandom 0.1.16",
"libc",
"rand_chacha 0.2.2",
"rand_core 0.5.1",
"rand_hc",
]
[[package]]
name = "rand"
version = "0.8.7"
@@ -4449,6 +4661,16 @@ dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "rand_chacha"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"
dependencies = [
"ppv-lite86",
"rand_core 0.5.1",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
@@ -4469,6 +4691,15 @@ dependencies = [
"rand_core 0.9.5",
]
[[package]]
name = "rand_core"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"
dependencies = [
"getrandom 0.1.16",
]
[[package]]
name = "rand_core"
version = "0.6.4"
@@ -4493,6 +4724,15 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_hc"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"
dependencies = [
"rand_core 0.5.1",
]
[[package]]
name = "rcgen"
version = "0.14.10"
@@ -4609,7 +4849,9 @@ dependencies = [
"base64 0.22.1",
"bytes",
"encoding_rs",
"futures-channel",
"futures-core",
"futures-util",
"h2 0.4.19",
"http 1.4.2",
"http-body 1.0.1",
@@ -4628,10 +4870,10 @@ dependencies = [
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
"sync_wrapper 1.0.2",
"tokio",
"tokio-native-tls",
"tower",
"tower 0.5.3",
"tower-http 0.6.11",
"tower-service",
"url",
@@ -4749,6 +4991,19 @@ dependencies = [
"nom",
]
[[package]]
name = "rustix"
version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [
"bitflags 2.13.0",
"errno",
"libc",
"linux-raw-sys 0.4.15",
"windows-sys 0.59.0",
]
[[package]]
name = "rustix"
version = "1.1.4"
@@ -4758,7 +5013,7 @@ dependencies = [
"bitflags 2.13.0",
"errno",
"libc",
"linux-raw-sys",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
]
@@ -4802,6 +5057,15 @@ dependencies = [
"security-framework",
]
[[package]]
name = "rustls-pemfile"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c"
dependencies = [
"base64 0.21.7",
]
[[package]]
name = "rustls-pemfile"
version = "2.2.0"
@@ -5428,6 +5692,12 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160"
[[package]]
name = "sync_wrapper"
version = "1.0.2"
@@ -5486,6 +5756,12 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417"
[[package]]
name = "take_mut"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f764005d11ee5f36500a149ace24e00e3da98b0158b3e2d53a7495660d3f4d60"
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -5495,7 +5771,7 @@ dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"rustix 1.1.4",
"windows-sys 0.61.2",
]
@@ -5558,6 +5834,35 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "tikv-client"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c62c2bb14a0b248e1d03a9357fac74b148edfc6190fbb04cc7c332eb50d7995d"
dependencies = [
"async-recursion",
"async-trait",
"derive-new",
"either",
"fail",
"futures",
"lazy_static",
"log",
"pin-project",
"prometheus 0.13.4",
"prost",
"rand 0.8.7",
"regex",
"semver",
"serde",
"serde_derive",
"serde_json",
"take_mut",
"thiserror 1.0.69",
"tokio",
"tonic",
]
[[package]]
name = "time"
version = "0.3.53"
@@ -5630,6 +5935,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-io-timeout"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bd86198d9ee903fedd2f9a2e72014287c0d9167e4ae43b5853007205dda1b76"
dependencies = [
"pin-project-lite",
"tokio",
]
[[package]]
name = "tokio-macros"
version = "2.7.0"
@@ -5718,6 +6033,57 @@ dependencies = [
"tokio",
]
[[package]]
name = "tonic"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d560933a0de61cf715926b9cac824d4c883c2c43142f787595e48280c40a1d0e"
dependencies = [
"async-stream",
"async-trait",
"axum 0.6.20",
"base64 0.21.7",
"bytes",
"flate2",
"h2 0.3.27",
"http 0.2.12",
"http-body 0.4.6",
"hyper 0.14.32",
"hyper-timeout 0.4.1",
"percent-encoding",
"pin-project",
"prost",
"rustls 0.21.12",
"rustls-pemfile 1.0.4",
"tokio",
"tokio-rustls 0.24.1",
"tokio-stream",
"tower 0.4.13",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tower"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"
dependencies = [
"futures-core",
"futures-util",
"indexmap 1.9.3",
"pin-project",
"pin-project-lite",
"rand 0.8.7",
"slab",
"tokio",
"tokio-util",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tower"
version = "0.5.3"
@@ -5727,7 +6093,7 @@ dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
"sync_wrapper",
"sync_wrapper 1.0.2",
"tokio",
"tokio-util",
"tower-layer",
@@ -5754,7 +6120,7 @@ dependencies = [
"pin-project-lite",
"tokio",
"tokio-util",
"tower",
"tower 0.5.3",
"tower-layer",
"tower-service",
"tracing",
@@ -6004,6 +6370,12 @@ dependencies = [
"try-lock",
]
[[package]]
name = "wasi"
version = "0.9.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
+1 -2
View File
@@ -73,6 +73,5 @@ 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"] }
tikv-client = "0.4.0"
+1 -1
View File
@@ -2,7 +2,7 @@ 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".
storage: "tikv://192.168.1.1:2379" # Storage backend: "memory", "hybrid", tikv://host1:2379,host2:2379 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".
+1
View File
@@ -1,3 +1,4 @@
pub mod hybrid;
pub mod redis;
pub mod tikv;
pub mod types;
+248
View File
@@ -0,0 +1,248 @@
use async_trait::async_trait;
use bytes::Bytes;
use log::warn;
use pingora_cache::storage::{HandleHit, HandleMiss, MissFinishType};
use pingora_cache::trace::SpanHandle;
use pingora_cache::{CacheKey, CacheMeta, HitHandler, MissHandler, PurgeOutcome, PurgeTarget, PurgeType, Storage};
use std::any::Any;
use std::borrow::Cow;
use tikv_client::{Error as TiKVError, RawClient};
#[derive(Clone)]
pub struct TiKVCache {
pub client: RawClient,
pub ttl: u64,
}
pub struct TiKVHitHandler {
body: Option<Bytes>,
}
pub struct TiKVMissHandler {
client: RawClient,
body_key: String,
body_buffer: Vec<u8>,
ttl: u64,
}
impl TiKVCache {
pub async fn new<S: Into<String>>(endpoints: Vec<S>, ttl: u64) -> Result<Self, TiKVError> {
let pd_endpoints: Vec<String> = endpoints.into_iter().map(Into::into).collect();
let client = RawClient::new(pd_endpoints).await?;
Ok(Self { client, ttl })
}
pub fn make_key(key: &CacheKey) -> Cow<'_, str> {
match key.primary_key_str() {
Some(s) => Cow::Borrowed(s),
None => Cow::Owned(key.primary_key().iter().map(|b| format!("{:02x}", b)).collect()),
}
}
}
#[async_trait]
impl HandleHit for TiKVHitHandler {
async fn read_body(&mut self) -> pingora::Result<Option<Bytes>> {
Ok(self.body.take())
}
async fn finish(self: Box<Self>, _storage: &'static (dyn Storage + Sync), _key: &CacheKey, _trace: &SpanHandle) -> pingora::Result<()> {
Ok(())
}
fn can_seek(&self) -> bool {
false
}
fn seek(&mut self, _start: usize, _end: Option<usize>) -> pingora::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<pingora_cache::eviction::CacheEntryId> {
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 TiKVMissHandler {
async fn write_body(&mut self, data: Bytes, _eof: bool) -> pingora::Result<()> {
self.body_buffer.extend_from_slice(&data);
Ok(())
}
async fn finish(self: Box<Self>) -> pingora::Result<MissFinishType> {
let len = self.body_buffer.len();
if let Err(e) = self.client.put_with_ttl(self.body_key, self.body_buffer, self.ttl).await {
warn!("Failed to write cache entry to TiKV: {e}");
}
Ok(MissFinishType::Appended(len, None))
}
fn entry_id(&self) -> Option<pingora_cache::eviction::CacheEntryId> {
None
}
}
#[async_trait]
impl Storage for TiKVCache {
async fn lookup(&'static self, key: &CacheKey, _trace: &SpanHandle) -> pingora::Result<Option<(CacheMeta, HitHandler)>> {
let base = Self::make_key(key);
let mut meta_key = String::with_capacity(base.len() + 5);
meta_key.push_str(&base);
meta_key.push_str(":meta");
let mut body_key = String::with_capacity(base.len() + 5);
body_key.push_str(&base);
body_key.push_str(":body");
let mut internal_key = String::with_capacity(meta_key.len() + 9);
internal_key.push_str(&meta_key);
internal_key.push_str(":internal");
let mut header_key = String::with_capacity(meta_key.len() + 7);
header_key.push_str(&meta_key);
header_key.push_str(":header");
let conn = (&self.client).clone();
// Perform a single batch_get round-trip for all 3 keys.
// We pass clones into batch_get, leaving original keys owned for potential cleanup.
let keys_to_fetch = vec![internal_key.clone(), header_key.clone(), body_key.clone()];
let results = match conn.batch_get(keys_to_fetch.clone()).await {
Ok(res) => res,
Err(_) => return Ok(None),
};
// Pre-convert expected keys to tikv_client::Key for matching
let expected_internal: tikv_client::Key = internal_key.clone().into();
let expected_header: tikv_client::Key = header_key.clone().into();
let expected_body: tikv_client::Key = body_key.clone().into();
let mut internal_bytes = None;
let mut header_bytes = None;
let mut body_bytes = None;
for kv in results {
let k = kv.key();
if k == &expected_internal {
internal_bytes = Some(kv.into_value());
} else if k == &expected_header {
header_bytes = Some(kv.into_value());
} else if k == &expected_body {
body_bytes = Some(kv.into_value());
}
}
match (internal_bytes, header_bytes, body_bytes) {
(Some(internal_vec), Some(header_vec), Some(body_vec)) => {
match CacheMeta::deserialize(&internal_vec, &header_vec) {
Ok(meta) => {
let handler: HitHandler = Box::new(TiKVHitHandler {
body: Some(Bytes::from(body_vec)),
});
Ok(Some((meta, handler)))
}
Err(_) => {
// Original keys are still owned here, no extra clones needed for batch_delete!
let _ = conn.batch_delete(vec![internal_key, header_key, body_key]).await;
Ok(None)
}
}
}
_ => Ok(None),
}
}
async fn get_miss_handler(&'static self, key: &CacheKey, meta: &CacheMeta, _trace: &SpanHandle) -> pingora::Result<MissHandler> {
let base = Self::make_key(key);
let mut meta_key = String::with_capacity(base.len() + 5);
meta_key.push_str(&base);
meta_key.push_str(":meta");
let mut body_key = String::with_capacity(base.len() + 5);
body_key.push_str(&base);
body_key.push_str(":body");
let mut internal_key = String::with_capacity(meta_key.len() + 9);
internal_key.push_str(&meta_key);
internal_key.push_str(":internal");
let mut header_key = String::with_capacity(meta_key.len() + 7);
header_key.push_str(&meta_key);
header_key.push_str(":header");
let ttl = self.ttl;
let (internal_bytes, header_bytes) = meta.serialize()?;
let conn = (&self.client).clone();
if let Err(e) = conn.put_with_ttl(internal_key, internal_bytes, ttl).await {
log::error!("Failed to cache body to TiKV: {}", e);
}
if let Err(e) = conn.put_with_ttl(header_key, header_bytes, ttl).await {
log::error!("Failed to cache headers to TiKV: {}", e);
}
Ok(Box::new(TiKVMissHandler {
client: self.client.clone(),
body_key,
body_buffer: Vec::with_capacity(4096),
ttl,
}))
}
async fn purge(&'static self, _target: PurgeTarget<'_>, _purge_type: PurgeType, _trace: &SpanHandle) -> pingora::Result<PurgeOutcome> {
Ok(PurgeOutcome::NotFound)
}
async fn update_meta(&'static self, key: &CacheKey, meta: &CacheMeta, _trace: &SpanHandle) -> pingora::Result<bool> {
let base = Self::make_key(key);
let mut meta_key = String::with_capacity(base.len() + 5);
meta_key.push_str(&base);
meta_key.push_str(":meta");
let mut internal_key = String::with_capacity(meta_key.len() + 9);
internal_key.push_str(&meta_key);
internal_key.push_str(":internal");
let mut header_key = String::with_capacity(meta_key.len() + 7);
header_key.push_str(&meta_key);
header_key.push_str(":header");
let ttl = self.ttl;
match meta.serialize() {
Ok((internal_bytes, header_bytes)) => {
let conn = (&self.client).clone();
let _ = conn.put_with_ttl(internal_key, internal_bytes, ttl).await;
let _ = conn.put_with_ttl(header_key, header_bytes, ttl).await;
Ok(true)
}
Err(_) => Ok(false),
}
}
fn support_streaming_partial_write(&self) -> bool {
false
}
fn as_any(&self) -> &(dyn Any + Send + Sync) {
self
}
}
+14 -44
View File
@@ -1,5 +1,6 @@
use crate::cache::hybrid::{FoyerCache, foy_init};
use crate::cache::redis::RedisCache;
use crate::cache::tikv::TiKVCache;
use crate::utils::lazylock::{CACHE_TTL, EVICTION};
use crate::utils::types::AppConfig;
use log::{error, info, warn};
@@ -36,6 +37,19 @@ pub async fn init_cache(config: Arc<AppConfig>) {
}
Err(e) => log::error!("Cache storage initialization failed: {}", e),
},
"tikv" => {
let stor = storage.replace("tikv://", "");
let endpoints: Vec<String> = stor.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
match TiKVCache::new(endpoints, 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);
@@ -57,48 +71,4 @@ pub async fn init_cache(config: Arc<AppConfig>) {
} 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);
// }
// }
}