diff --git a/Cargo.lock b/Cargo.lock index 01b85ea8..698301bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -615,7 +615,7 @@ dependencies = [ "num-traits", "serde", "wasm-bindgen", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1651,7 +1651,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -1874,7 +1874,7 @@ dependencies = [ "simd_cesu8", "thiserror 2.0.20", "walkdir", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1974,6 +1974,15 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +[[package]] +name = "libmimalloc-sys" +version = "0.1.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9" +dependencies = [ + "cc", +] + [[package]] name = "libsqlite3-sys" version = "0.38.2" @@ -2054,6 +2063,15 @@ dependencies = [ "rustix", ] +[[package]] +name = "mimalloc" +version = "0.1.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862" +dependencies = [ + "libmimalloc-sys", +] + [[package]] name = "mime" version = "0.3.17" @@ -2147,6 +2165,15 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -2180,6 +2207,25 @@ dependencies = [ "autocfg", ] +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "object" version = "0.40.0" @@ -2242,7 +2288,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3270,6 +3316,20 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "sysinfo" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252800745060e7b9ffb7b2badbd8b31cfa4aa2e61af879d0a3bf2a317c20217d" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + [[package]] name = "target-lexicon" version = "0.13.5" @@ -3670,7 +3730,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.88.0" +version = "0.89.0" dependencies = [ "serde", "serde_json", @@ -3681,7 +3741,7 @@ dependencies = [ [[package]] name = "tw-bedrock" -version = "0.88.0" +version = "0.89.0" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -3702,7 +3762,7 @@ dependencies = [ [[package]] name = "tw-breaker" -version = "0.88.0" +version = "0.89.0" dependencies = [ "serde", "serde_json", @@ -3710,7 +3770,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.88.0" +version = "0.89.0" dependencies = [ "blake3", "libc", @@ -3736,7 +3796,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.88.0" +version = "0.89.0" dependencies = [ "axum", "base64 0.22.1", @@ -3782,7 +3842,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.88.0" +version = "0.89.0" dependencies = [ "memchr", "serde", @@ -3791,7 +3851,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.88.0" +version = "0.89.0" dependencies = [ "chrono", "serde", @@ -3805,7 +3865,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.88.0" +version = "0.89.0" dependencies = [ "arc-swap", "async-stream", @@ -3831,6 +3891,7 @@ dependencies = [ "serde_json", "serde_yaml_ng", "sha2 0.11.0", + "sysinfo", "tempfile", "thiserror 2.0.20", "tokio", @@ -3856,7 +3917,7 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.88.0" +version = "0.89.0" dependencies = [ "aho-corasick", "base64 0.22.1", @@ -3877,7 +3938,7 @@ dependencies = [ [[package]] name = "tw-handover" -version = "0.88.0" +version = "0.89.0" dependencies = [ "libc", "serde", @@ -3890,7 +3951,7 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.88.0" +version = "0.89.0" dependencies = [ "serde", "serde_json", @@ -3904,7 +3965,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.88.0" +version = "0.89.0" dependencies = [ "tokio", "tracing", @@ -3913,7 +3974,7 @@ dependencies = [ [[package]] name = "tw-pack" -version = "0.88.0" +version = "0.89.0" dependencies = [ "age", "blake3", @@ -3937,7 +3998,7 @@ dependencies = [ [[package]] name = "tw-plugin" -version = "0.88.0" +version = "0.89.0" dependencies = [ "libc", "rand 0.10.2", @@ -3953,7 +4014,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.88.0" +version = "0.89.0" dependencies = [ "arc-swap", "flate2", @@ -3966,14 +4027,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.88.0" +version = "0.89.0" dependencies = [ "thiserror 2.0.20", ] [[package]] name = "tw-store" -version = "0.88.0" +version = "0.89.0" dependencies = [ "blake3", "bytes", @@ -3993,7 +4054,7 @@ dependencies = [ [[package]] name = "tw-sync" -version = "0.88.0" +version = "0.89.0" dependencies = [ "age", "axum", @@ -4021,7 +4082,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.88.0" +version = "0.89.0" dependencies = [ "serde", "serde_json", @@ -4030,7 +4091,7 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.88.0" +version = "0.89.0" dependencies = [ "libc", "notify", @@ -4041,7 +4102,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.88.0" +version = "0.89.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -4051,7 +4112,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.88.0" +version = "0.89.0" dependencies = [ "anyhow", "axum", @@ -4062,6 +4123,7 @@ dependencies = [ "hyper", "hyper-util", "libc", + "mimalloc", "reqwest", "serde", "serde_json", @@ -4580,6 +4642,22 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -4589,6 +4667,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "winch-codegen" version = "49.0.5" @@ -4608,6 +4692,41 @@ dependencies = [ "wasmtime-internal-cranelift", ] +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections", + "windows-core 0.61.2", + "windows-future", + "windows-link 0.1.3", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -4616,9 +4735,20 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement", "windows-interface", - "windows-link", - "windows-result", - "windows-strings", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading", ] [[package]] @@ -4643,19 +4773,53 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows-result" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -4664,7 +4828,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4691,7 +4855,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4716,7 +4880,7 @@ version = "0.53.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ - "windows-link", + "windows-link 0.2.1", "windows_aarch64_gnullvm 0.53.1", "windows_aarch64_msvc 0.53.1", "windows_i686_gnu 0.53.1", @@ -4727,6 +4891,15 @@ dependencies = [ "windows_x86_64_msvc 0.53.1", ] +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" diff --git a/Cargo.toml b/Cargo.toml index a333129c..e089d1d3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,7 +61,7 @@ categories = ["network-programming", "web-programming::http-server"] # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.88.0" +version = "0.89.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── @@ -89,6 +89,8 @@ tw-handover = { path = "crates/tw-handover" } # ── 版本与企业版 workspace 对齐,便于反向依赖时不打架 ──── tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync", "io-util", "signal"] } +# 只读内存容量和 Linux cgroup 限额,不扫描进程,也不开采集线程。 +sysinfo = { version = "0.36", default-features = false, features = ["system"] } axum = { version = "0.8", features = ["macros", "ws"] } tower = "0.5" hyper = { version = "1", features = ["full"] } diff --git a/bin/twcore/Cargo.toml b/bin/twcore/Cargo.toml index 66c556dd..4c5b3f7c 100644 --- a/bin/twcore/Cargo.toml +++ b/bin/twcore/Cargo.toml @@ -13,7 +13,14 @@ description = "Self-contained AI gateway: the local engine behind ThinkWatch Lit keywords.workspace = true categories.workspace = true +[features] +default = ["mimalloc"] +# 系统分配器的构建只用于对照诊断;发布包默认启用,无需用户设置。 +mimalloc = ["dep:mimalloc"] + [dependencies] +# Linux 不主动申请 THP,避免小对象/线程堆按大页驻留;不要求用户设置内核或环境变量。 +mimalloc = { version = "0.1.52", optional = true, features = ["no_thp"] } tw-config = { workspace = true } tw-control = { workspace = true } # 升级不断线:新旧 core 之间的交接连接 diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 83aaa576..6b99cd40 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -18,12 +18,17 @@ mod lockfile; mod pack_cli; mod proc; mod record; +mod runtime; mod sync_cmd; mod upgrade; use background::Background; use lockfile::{LockFile, LockOutcome}; +#[cfg(feature = "mimalloc")] +#[global_allocator] +static ALLOCATOR: mimalloc::MiMalloc = mimalloc::MiMalloc; + #[derive(Parser)] // `about` 不写值就是 Cargo.toml 里的 description:一句话只写一处,两边不会各说各的 #[command(name = "twcore", version, about)] @@ -256,6 +261,7 @@ fn main() -> Result<()> { }), ) .init(); + runtime::init_allocator(); // 网关的代码 panic 时,那个请求的结局写得出哪一行、为什么(stderr 在桌面版里没人看) tw_gateway::panic_note::install(); @@ -394,7 +400,9 @@ fn fmt_time(ms: u64) -> String { /// 数字准不准。 fn cmd_speed(path: &Path, provider: Option, proxy: Option) -> Result<()> { let cfg = tw_config::load(path).with_context(|| format!("reading {}", path.display()))?; - let rt = tokio::runtime::Runtime::new()?; + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; rt.block_on(async move { if let Some(name) = proxy { let px = cfg @@ -792,9 +800,7 @@ fn cmd_serve(path: &Path, port: Option, safe: bool, parent: Option) -> // 端口文件)都会顺手 `create_dir_all`,谁先到谁建 —— 而 Windows 上「谁 // 建的」决定了它的 ACL,也就决定了那份明文密钥同机的其他用户读不读得到。 tw_config::private_dir::create(&dir).with_context(|| format!("creating {}", dir.display()))?; - let rt = tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build()?; + let rt = runtime::build()?; // **锁被一个活着的 core 占着时,先问它是不是在等接替者**(升级不断线,见 `handover`)。 // 是的话接管它;不是的话照旧报「已有实例在运行」 let (mut lock, mut incoming) = match LockFile::acquire(&dir)? { diff --git a/bin/twcore/src/runtime.rs b/bin/twcore/src/runtime.rs new file mode 100644 index 00000000..2ff0df95 --- /dev/null +++ b/bin/twcore/src/runtime.rs @@ -0,0 +1,95 @@ +//! 网关的运行时按机器自动定规模;任务由 Tokio 调度,用户无需写 runtime 配置。 + +use anyhow::{Context, Result}; + +/// Linux 的 THP 会把小对象所在的稀疏堆按 2 MiB 驻留,抵消线程回收的收益。 +/// 只约束本进程,不改系统设置,也不要求用户提供分配器环境变量。 +pub fn init_allocator() { + #[cfg(all(target_os = "linux", feature = "mimalloc"))] + { + // SAFETY: PR_SET_THP_DISABLE 只接受整数参数,不读写 Rust 的内存。 + // 必须在创建工作线程之前调用,使其继承该进程的策略。 + let result = unsafe { + libc::prctl( + libc::PR_SET_THP_DISABLE, + 1 as libc::c_ulong, + 0 as libc::c_ulong, + 0 as libc::c_ulong, + 0 as libc::c_ulong, + ) + }; + if result != 0 { + tracing::debug!(error = %std::io::Error::last_os_error(), "could not disable transparent huge pages"); + } + } +} + +pub fn build() -> Result { + let policy = tw_gateway::resources::policy(); + // 保留 Tokio 原有的显式覆盖,但自动值本身就适用于大核服务器。 + let workers = workers( + policy.workers, + std::env::var("TOKIO_WORKER_THREADS").ok().as_deref(), + )?; + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(workers) + .thread_keep_alive(tw_gateway::resources::CPU_KEEP_ALIVE) + .enable_all() + .build()?; + tracing::info!( + workers, + heavy_jobs = policy.heavy_jobs, + cpu_idle_seconds = tw_gateway::resources::CPU_KEEP_ALIVE.as_secs(), + body_budget_mib = policy.body_budget / (1024 * 1024), + allocator = if cfg!(feature = "mimalloc") { + "mimalloc" + } else { + "system" + }, + "automatically sized gateway runtime" + ); + Ok(rt) +} + +fn workers(automatic: usize, explicit: Option<&str>) -> Result { + match explicit { + None => Ok(automatic), + Some(value) => value + .parse::() + .map(usize::from) + .with_context(|| { + format!("TOKIO_WORKER_THREADS must be a positive integer, got `{value}`") + }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(all(target_os = "linux", feature = "mimalloc"))] + #[test] + fn allocator_disables_transparent_huge_pages_for_this_process() { + init_allocator(); + // SAFETY: PR_GET_THP_DISABLE returns the process flag and takes integer arguments. + let disabled = unsafe { + libc::prctl( + libc::PR_GET_THP_DISABLE, + 0 as libc::c_ulong, + 0 as libc::c_ulong, + 0 as libc::c_ulong, + 0 as libc::c_ulong, + ) + }; + assert_eq!(disabled, 1); + } + + #[test] + fn explicit_tokio_override_is_optional_and_validated() { + assert_eq!(workers(8, None).unwrap(), 8); + assert_eq!(workers(8, Some("16")).unwrap(), 16); + for bad in ["0", "", "-1", "eight"] { + assert!(workers(8, Some(bad)).is_err()); + } + } +} diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 9a24df93..eab7bcfa 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -425,6 +425,7 @@ gw.request.body_declared_too_large gw.request.body_over_limit gw.request.body_unreadable gw.request.decoded_body_over_limit +gw.request.memory_busy gw.request.unsupported_encoding gw.route.all_selected_disabled gw.route.denied diff --git a/crates/tw-gateway/Cargo.toml b/crates/tw-gateway/Cargo.toml index 29240ee1..9683a125 100644 --- a/crates/tw-gateway/Cargo.toml +++ b/crates/tw-gateway/Cargo.toml @@ -51,6 +51,7 @@ tw-dialect = { workspace = true } tw-plugin = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } +sysinfo = { workspace = true } tracing = { workspace = true } zstd = { workspace = true } # 压缩过的请求体和上游回答:gzip、deflate 用它解,zstd 用上面那个 diff --git a/crates/tw-gateway/src/content.rs b/crates/tw-gateway/src/content.rs index aad046fb..2e5ae9f0 100644 --- a/crates/tw-gateway/src/content.rs +++ b/crates/tw-gateway/src/content.rs @@ -947,7 +947,13 @@ async fn redact(raw: Bytes, r: Redaction) -> String { let heavy = raw.len() >= HEAVY; let go = move || r.apply(&String::from_utf8_lossy(&raw)); if heavy { - tokio::task::spawn_blocking(go).await.unwrap_or_default() + let slot = crate::resources::heavy_slot().await; + tokio::task::spawn_blocking(move || { + let _slot = slot; + go() + }) + .await + .unwrap_or_default() } else { go() } diff --git a/crates/tw-gateway/src/inflate.rs b/crates/tw-gateway/src/inflate.rs index c77fd557..831b3e91 100644 --- a/crates/tw-gateway/src/inflate.rs +++ b/crates/tw-gateway/src/inflate.rs @@ -30,6 +30,8 @@ pub enum Coding { pub enum Decode { /// 解出来的超过了上限 OverLimit, + /// 进程的正文缓冲预算暂时用满了,客户端可以稍后重试 + Busy, /// 数据和编码对不上、解到一半断了 Failed(String), } @@ -57,6 +59,16 @@ impl Coding { /// 解开 `raw`,解出来的最多 `max` 字节。**读到第 `max + 1` 个字节就停**:解出来的有多大, /// 压缩数据自己说了不算(zstd 的帧头可以写一个假的长度),只信实际解出来的 pub fn decode(self, raw: &[u8], max: usize) -> Result { + self.decode_with(raw, max, |_| Ok(())) + } + + /// 解压输出每次增长前预留预算,不信压缩帧自报的长度。 + pub(crate) fn decode_with( + self, + raw: &[u8], + max: usize, + mut reserve: impl FnMut(usize) -> Result<(), Decode>, + ) -> Result { let reader: Box = match self { Self::Gzip => Box::new(flate2::read::MultiGzDecoder::new(raw)), // HTTP 的 deflate 是 zlib 封装的(RFC 9110 §8.4.1.2) @@ -66,12 +78,21 @@ impl Coding { ), }; let mut out = Vec::new(); - reader - .take(max as u64 + 1) - .read_to_end(&mut out) - .map_err(|e| Decode::Failed(e.to_string()))?; - if out.len() > max { - return Err(Decode::OverLimit); + let mut reader = reader.take(max as u64 + 1); + let mut chunk = [0; 16 * 1024]; + loop { + let n = reader + .read(&mut chunk) + .map_err(|e| Decode::Failed(e.to_string()))?; + if n == 0 { + break; + } + let next = out.len().saturating_add(n); + if next > max { + return Err(Decode::OverLimit); + } + reserve(next)?; + out.extend_from_slice(&chunk[..n]); } Ok(Bytes::from(out)) } diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index c57114af..83150e6c 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -51,6 +51,7 @@ pub mod probe; mod pulse; pub mod quota; pub mod quote; +pub mod resources; pub mod retry; pub mod seal; pub mod sent; diff --git a/crates/tw-gateway/src/plugin/pool.rs b/crates/tw-gateway/src/plugin/pool.rs index 6dcec636..4e890c4d 100644 --- a/crates/tw-gateway/src/plugin/pool.rs +++ b/crates/tw-gateway/src/plugin/pool.rs @@ -2,10 +2,10 @@ //! //! 插件调用是阻塞的、吃 CPU 的(一次请求钩子最多跑两百毫秒)。放在 tokio 的工作线程 //! 上调,几个慢插件就能把整个数据面的线程占满 —— 那时连不走插件的请求也一起卡住。 -//! 所以一律交给这里:几根自己的线程,**排队的数量有上限**,满了的话调用方异步地等, +//! 所以一律交给这里:按需创建、空闲回收的专用线程,**排队的数量有上限**,满了调用方异步地等, //! 不占着 tokio 的线程。 //! -//! 线程**第一次用到时才起**:绝大多数用户一个插件都没装,不该为它多几根闲着的线程。 +//! 线程按实际并发创建,空闲十秒退出。上限取自动 CPU 预算,和网关重任务共用 CPU 名额。 //! //! # 回答实例的名额 //! @@ -17,15 +17,14 @@ //! 满了就按那个插件的 `on_error` 处置 —— 拒绝是这个请求失败,跳过是这次回答绕过它。 //! 名额跟着实例走([`Slot`]),实例扔掉的那一刻还回来。 -use std::sync::mpsc; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, OnceLock}; + +use tokio::runtime::{Builder, Runtime}; /// 同时活着的回答实例最多这么多个(见模块说明)。按一个实例 64 MiB 的上限算,最坏 /// 2 GiB;实际的插件一个实例多半不到 1 MiB pub const MAX_LIVE_REPLIES: usize = 32; -type Job = Box; - /// 池子坏了:任务 panic 了,或者线程起不来。 #[derive(Debug, Clone, PartialEq, Eq)] pub enum PoolError { @@ -50,7 +49,7 @@ pub struct Pool { replies: Arc, /// 名额一共几个 reply_cap: usize, - tx: OnceLock>, String>>, + runtime: OnceLock>, } /// 一个回答实例占着的名额(见 [`Pool::reply_slot`])。**和实例放在一起**:实例在哪儿被 @@ -80,7 +79,7 @@ impl Pool { permits: Arc::new(tokio::sync::Semaphore::new(queue.max(threads))), replies: Arc::new(tokio::sync::Semaphore::new(replies)), reply_cap: replies, - tx: OnceLock::new(), + runtime: OnceLock::new(), } } @@ -104,41 +103,27 @@ impl Pool { .saturating_sub(self.replies.available_permits()) } - /// 按机器的核数定:至少两根,最多八根;排队的是线程数的四倍。 + /// 线程按需创建,上限取机器的自动 CPU 预算;排队的是上限的四倍。 pub fn default_size() -> Self { - let cores = std::thread::available_parallelism().map_or(2, |n| n.get()); - let threads = cores.clamp(2, 8); - Self::new(threads, threads * 4) - } - - fn sender(&self) -> Result<&Mutex>, PoolError> { - self.tx - .get_or_init(|| { - let (tx, rx) = mpsc::channel::(); - let rx = Arc::new(Mutex::new(rx)); - for i in 0..self.threads { - let rx = rx.clone(); - std::thread::Builder::new() - .name(format!("tw-plugin-{i}")) - .stack_size(STACK) - .spawn(move || { - loop { - // 锁只在取任务时拿着,跑任务时放开 - let job = match rx.lock() { - Ok(r) => r.recv(), - Err(_) => return, - }; - match job { - Ok(job) => job(), - // 池子被丢掉了 - Err(_) => return, - } - } - }) - .map_err(|e| e.to_string())?; - } - Ok(Mutex::new(tx)) - }) + let threads = crate::resources::policy().heavy_jobs; + Self::new(threads, threads.saturating_mul(4)) + } + + fn builder(&self) -> Builder { + // 只用 Tokio 的弹性 blocking pool:current-thread runtime 不创建调度线程, + // 也不需要驱动 block_on。沙箱保留独立的 8 MiB 栈,不占普通文件/DNS 线程。 + let mut builder = Builder::new_current_thread(); + builder + .max_blocking_threads(self.threads) + .thread_name("tw-plugin-worker") + .thread_stack_size(STACK) + .thread_keep_alive(crate::resources::CPU_KEEP_ALIVE); + builder + } + + fn runtime(&self) -> Result<&Runtime, PoolError> { + self.runtime + .get_or_init(|| self.builder().build().map_err(|e| e.to_string())) .as_ref() .map_err(|e| PoolError::Unavailable(e.clone())) } @@ -156,20 +141,26 @@ impl Pool { .acquire_owned() .await .map_err(|e| PoolError::Unavailable(e.to_string()))?; - let (done, wait) = tokio::sync::oneshot::channel(); - let job: Job = Box::new(move || { - let _permit = permit; - let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) - .map_err(|_| PoolError::Panicked); - let _ = done.send(out); - }); - self.sender()? - .lock() + let cpu = crate::resources::heavy_slot().await; + self.runtime()? + .spawn_blocking(move || { + // 调用方取消也不能提前归还 CPU 和队列名额:阻塞调用仍会继续跑。 + let (_permit, _cpu) = (permit, cpu); + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) + .map_err(|_| PoolError::Panicked) + }) + .await .map_err(|e| PoolError::Unavailable(e.to_string()))? - .send(job) - .map_err(|e| PoolError::Unavailable(e.to_string()))?; - wait.await - .map_err(|_| PoolError::Unavailable("the plugin thread went away".into()))? + } +} + +impl Drop for Pool { + fn drop(&mut self) { + if let Some(Ok(runtime)) = self.runtime.take() { + // Pool 常在异步任务里随配置一起被丢掉;不能在这里阻塞关闭 runtime。 + // 已经开始的调用照样完成,随后线程全部退出。 + runtime.shutdown_background(); + } } } @@ -196,6 +187,75 @@ mod tests { assert_eq!(pool.run(|| 7).await, Ok(7)); } + #[tokio::test] + async fn threads_follow_demand_retire_and_can_be_created_again() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + + let pool = Arc::new(Pool::new(80, 80)); + let live = Arc::new(AtomicUsize::new(0)); + let (started, stopped) = (live.clone(), live.clone()); + let runtime = pool + .builder() + .thread_keep_alive(Duration::from_millis(100)) + .on_thread_start(move || { + started.fetch_add(1, Ordering::SeqCst); + }) + .on_thread_stop(move || { + stopped.fetch_sub(1, Ordering::SeqCst); + }) + .build() + .unwrap(); + pool.runtime.set(Ok(runtime)).unwrap(); + assert_eq!(live.load(Ordering::SeqCst), 0); + assert_eq!(pool.run(|| 42).await, Ok(42)); + assert_eq!(live.load(Ordering::SeqCst), 1, "do not prestart 80 threads"); + + let count = crate::resources::policy().heavy_jobs.min(12); + let release = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let (began, mut starts) = tokio::sync::mpsc::unbounded_channel(); + let mut jobs = Vec::new(); + for _ in 0..count { + let (pool, release, began) = (pool.clone(), release.clone(), began.clone()); + jobs.push(tokio::spawn(async move { + pool.run(move || { + began.send(()).unwrap(); + let guard = release.0.lock().unwrap(); + let _guard = release + .1 + .wait_timeout_while(guard, Duration::from_secs(10), |done| !*done) + .unwrap(); + }) + .await + .unwrap(); + })); + } + for _ in 0..count { + tokio::time::timeout(Duration::from_secs(5), starts.recv()) + .await + .unwrap() + .unwrap(); + } + assert_eq!(live.load(Ordering::SeqCst), count); + // 丢掉调用方不能让仍在执行的插件提前归还队列名额。 + jobs[0].abort(); + assert_eq!(pool.permits.available_permits(), 80 - count); + *release.0.lock().unwrap() = true; + release.1.notify_all(); + for job in jobs { + let _ = job.await; + } + tokio::time::timeout(Duration::from_secs(5), async { + while live.load(Ordering::SeqCst) != 0 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!(pool.permits.available_permits(), 80); + assert_eq!(pool.run(|| 7).await, Ok(7)); + } + #[test] fn reply_slots_run_out_without_waiting_and_come_back_when_dropped() { let pool = Pool::with_replies(1, 1, 2); diff --git a/crates/tw-gateway/src/resources.rs b/crates/tw-gateway/src/resources.rs new file mode 100644 index 00000000..d9ec5234 --- /dev/null +++ b/crates/tw-gateway/src/resources.rs @@ -0,0 +1,346 @@ +//! 进程级的自动资源调度。配置重载、多个运行时共用同一份预算。 +//! +//! CPU 重任务先异步等名额,再交给阻塞线程;等候者不会占满 Tokio 的线程。 +//! 正文按字节占预算,并为解析、复制留三倍余量。预算不足时先退避重试,避免已经 +//! 持有一半正文的请求互相等内存。名额跟着 Bytes 的最后一份引用归还。 +//! +//! 单个合法的大正文可以独占预算:自动预算不改变 256 MiB 的单请求上限。这是 +//! 正文缓冲的预算,不是对整个进程 RSS 的硬限制(插件、JSON 对象等另有开销)。 + +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Duration; + +use bytes::Bytes; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; + +#[cfg(any(target_os = "linux", test))] +mod cgroup; + +const MIB: usize = 1024 * 1024; +const BODY_HEADROOM: usize = 3; +const HEAVY_BODY: usize = 1024 * 1024; + +/// 突发负载过去后回收阻塞线程;不改变常驻 I/O worker。 +pub const CPU_KEEP_ALIVE: Duration = Duration::from_secs(10); + +#[derive(Debug)] +pub struct Policy { + pub workers: usize, + pub heavy_jobs: usize, + pub body_budget: usize, +} + +impl Policy { + fn for_machine(parallelism: usize, memory: u64) -> Self { + let workers = parallelism.clamp(1, 8); + let memory = usize::try_from(memory).unwrap_or(usize::MAX); + Self { + workers, + heavy_jobs: parallelism.max(1).min((memory / (128 * MIB)).max(1)), + body_budget: (memory / 8).clamp(64 * MIB, 512 * MIB), + } + } +} + +pub fn policy() -> &'static Policy { + static POLICY: OnceLock = OnceLock::new(); + POLICY.get_or_init(|| { + let parallelism = std::thread::available_parallelism().map_or(1, usize::from); + let mut system = sysinfo::System::new(); + system.refresh_memory(); + // Linux 容器要看 cgroup 限额,不能按宿主机的几十 GB 分预算。 + let cgroup_limit = system.cgroup_limits().map(|c| c.total_memory); + #[cfg(target_os = "linux")] + let cgroup_limit = cgroup::memory_limit().or(cgroup_limit); + let memory = effective_memory(system.total_memory(), cgroup_limit); + Policy::for_machine(parallelism, memory) + }) +} + +fn effective_memory(physical: u64, cgroup: Option) -> u64 { + let physical = if physical == 0 { + 1024 * MIB as u64 + } else { + physical + }; + cgroup + .filter(|&n| n > 0) + .map_or(physical, |n| n.min(physical)) +} + +/// 小任务允许占用一半 I/O worker;并发超过它时同样交还调度权,避免小正文流量 +/// 永远只能用常驻的八根线程。CPU 名额同时约束内联、阻塞和插件任务。 +struct Scheduler { + slots: Arc, + inline: Semaphore, +} + +impl Scheduler { + fn new(policy: &Policy) -> Self { + Self { + slots: Arc::new(Semaphore::new(policy.heavy_jobs)), + inline: Semaphore::new(policy.workers.div_ceil(2)), + } + } + + async fn slot(&self) -> OwnedSemaphorePermit { + self.slots + .clone() + .acquire_owned() + .await + .expect("the process-wide heavy-work semaphore is never closed") + } + + async fn run(&self, size: usize, f: impl FnOnce() -> T) -> T { + use tokio::runtime::{Handle, RuntimeFlavor}; + + let _slot = self.slot().await; + let inline = (size < HEAVY_BODY) + .then(|| self.inline.try_acquire().ok()) + .flatten(); + let multi = + Handle::try_current().is_ok_and(|h| h.runtime_flavor() == RuntimeFlavor::MultiThread); + if inline.is_some() || !multi { + f() + } else { + // 原线程执行借用栈上的闭包,Tokio 按需起替补线程继续处理 I/O。 + // 空闲线程按 runtime 的 keep-alive 回收;I/O worker 数不是 CPU 并发上限。 + tokio::task::block_in_place(f) + } + } +} + +fn scheduler() -> &'static Scheduler { + static SCHEDULER: OnceLock = OnceLock::new(); + SCHEDULER.get_or_init(|| Scheduler::new(policy())) +} + +pub(crate) async fn heavy_slot() -> OwnedSemaphorePermit { + scheduler().slot().await +} + +pub(crate) async fn heavy(size: usize, f: impl FnOnce() -> T) -> T { + scheduler().run(size, f).await +} + +pub(crate) fn body_budget() -> &'static Arc { + static BUDGET: OnceLock> = OnceLock::new(); + BUDGET.get_or_init(|| Budget::new(policy().body_budget)) +} + +pub(crate) struct Budget { + limit: usize, + used: Mutex, +} + +impl Budget { + pub(crate) fn new(limit: usize) -> Arc { + Arc::new(Self { + limit, + used: Mutex::new(0), + }) + } + + pub(crate) fn reserve(self: &Arc) -> Reservation { + Reservation { + budget: self.clone(), + charged: 0, + } + } +} + +pub(crate) struct Reservation { + budget: Arc, + charged: usize, +} + +impl Reservation { + /// 在追加正文或解压输出之前调用。失败不会改变已经占用的预算。 + pub(crate) fn grow(&mut self, bytes: usize) -> bool { + let charge = bytes.saturating_mul(BODY_HEADROOM).min(self.budget.limit); + let extra = charge.saturating_sub(self.charged); + let mut used = self.budget.used.lock().unwrap_or_else(|e| e.into_inner()); + if extra > self.budget.limit - *used { + return false; + } + *used += extra; + self.charged += extra; + true + } + + pub(crate) fn wrap(self, data: Bytes) -> Bytes { + Bytes::from_owner(Buffered { + data, + _reservation: self, + }) + } +} + +impl Drop for Reservation { + fn drop(&mut self) { + let mut used = self.budget.used.lock().unwrap_or_else(|e| e.into_inner()); + *used -= self.charged; + } +} + +struct Buffered { + data: Bytes, + _reservation: Reservation, +} + +impl AsRef<[u8]> for Buffered { + fn as_ref(&self) -> &[u8] { + &self.data + } +} + +pub(crate) fn memory_busy() -> crate::GatewayError { + crate::GatewayError::busy(tw_types::msg!( + "gw.request.memory_busy" => + "The gateway is processing large requests. Please retry shortly." + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn automatic_policy_handles_small_machines_and_many_cores() { + let small = Policy::for_machine(1, 256 * MIB as u64); + assert_eq!( + (small.workers, small.heavy_jobs, small.body_budget), + (1, 1, 64 * MIB) + ); + let large = Policy::for_machine(80, 128 * 1024 * MIB as u64); + assert_eq!( + (large.workers, large.heavy_jobs, large.body_budget), + (8, 80, 512 * MIB) + ); + assert_eq!(Policy::for_machine(80, 256 * MIB as u64).heavy_jobs, 2); + } + + #[test] + fn eighty_cpu_jobs_scale_past_two_io_workers_and_retire_when_idle() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Instant; + + // 模拟 80 核策略,验证真实线程并发和回收;不要求测试机有 80 个物理核。 + let live = Arc::new(AtomicUsize::new(0)); + let (started, stopped) = (live.clone(), live.clone()); + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_keep_alive(Duration::from_millis(100)) + .on_thread_start(move || { + started.fetch_add(1, Ordering::SeqCst); + }) + .on_thread_stop(move || { + stopped.fetch_sub(1, Ordering::SeqCst); + }) + .enable_all() + .build() + .unwrap(); + let scheduler = Arc::new(Scheduler::new(&Policy { + workers: 2, + ..Policy::for_machine(80, 128 << 30) + })); + // 大正文必定交出调度权;小正文在并发扫描时也应扩展。 + for size in [HEAVY_BODY, 32 * 1024] { + rt.block_on(async { + let release = Arc::new((Mutex::new(false), std::sync::Condvar::new())); + let (began, mut starts) = tokio::sync::mpsc::unbounded_channel(); + let mut jobs = Vec::new(); + for _ in 0..80 { + let (scheduler, release, began) = + (scheduler.clone(), release.clone(), began.clone()); + jobs.push(tokio::spawn(async move { + scheduler + .run(size, || { + began.send(()).unwrap(); + let guard = release.0.lock().unwrap(); + let _guard = release + .1 + .wait_timeout_while(guard, Duration::from_secs(10), |done| { + !*done + }) + .unwrap(); + }) + .await; + })); + } + for _ in 0..80 { + tokio::time::timeout(Duration::from_secs(5), starts.recv()) + .await + .expect("all 80 jobs must run concurrently") + .unwrap(); + } + assert_eq!(scheduler.slots.available_permits(), 0); + assert!(live.load(Ordering::SeqCst) >= 80); + // 已有 80 个 CPU 调用时,I/O 的计时器还能正常推进。 + tokio::time::sleep(Duration::from_millis(10)).await; + *release.0.lock().unwrap() = true; + release.1.notify_all(); + for job in jobs { + job.await.unwrap(); + } + }); + let deadline = Instant::now() + Duration::from_secs(5); + while live.load(Ordering::SeqCst) != 2 && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!( + live.load(Ordering::SeqCst), + 2, + "only I/O workers stay alive" + ); + } + } + + #[test] + fn container_memory_caps_host_memory_and_unknown_values_have_a_fallback() { + assert_eq!(effective_memory(64 << 30, Some(512 << 20)), 512 << 20); + assert_eq!(effective_memory(1 << 30, Some(u64::MAX)), 1 << 30); + assert_eq!(effective_memory(0, Some(0)), 1 << 30); + } + + #[test] + fn reservations_survive_bytes_clones_and_slices() { + let budget = Budget::new(30); + let mut reservation = budget.reserve(); + assert!(reservation.grow(5)); + let data = reservation.wrap(Bytes::from_static(b"hello")); + let clone = data.clone(); + let slice = clone.slice(1..3); + drop(data); + drop(clone); + assert_eq!(*budget.used.lock().unwrap(), 15); + assert_eq!(&slice[..], b"el"); + drop(slice); + assert_eq!(*budget.used.lock().unwrap(), 0); + } + + #[test] + fn failed_growth_releases_only_its_own_reservation() { + let budget = Budget::new(30); + let mut first = budget.reserve(); + let mut second = budget.reserve(); + assert!(first.grow(6)); + assert!(second.grow(4)); + assert!(!first.grow(7)); + drop(second); + assert!(first.grow(7)); + drop(first); + assert_eq!(*budget.used.lock().unwrap(), 0); + } + + #[test] + fn a_large_legal_body_can_run_exclusively_without_deadlocking() { + let budget = Budget::new(30); + let mut large = budget.reserve(); + assert!(large.grow(100)); + let mut small = budget.reserve(); + assert!(!small.grow(1)); + drop(large); + assert!(small.grow(1)); + } +} diff --git a/crates/tw-gateway/src/resources/cgroup.rs b/crates/tw-gateway/src/resources/cgroup.rs new file mode 100644 index 00000000..72ae6aa1 --- /dev/null +++ b/crates/tw-gateway/src/resources/cgroup.rs @@ -0,0 +1,89 @@ +//! 同时看当前 cgroup 和它的祖先,systemd 的子组也不能越过父组的内存限额。 + +use std::path::{Component, Path}; + +#[cfg(target_os = "linux")] +pub(super) fn memory_limit() -> Option { + let membership = std::fs::read_to_string("/proc/self/cgroup").ok()?; + membership + .lines() + .filter_map(|line| { + let mut fields = line.splitn(3, ':'); + let hierarchy = fields.next()?; + let controllers = fields.next()?; + let path = fields.next()?; + if hierarchy == "0" && controllers.is_empty() { + lowest_limit(Path::new("/sys/fs/cgroup"), Path::new(path), "memory.max") + } else if controllers.split(',').any(|c| c == "memory") { + lowest_limit( + Path::new("/sys/fs/cgroup/memory"), + Path::new(path), + "memory.limit_in_bytes", + ) + } else { + None + } + }) + .min() +} + +fn lowest_limit(root: &Path, membership: &Path, file: &str) -> Option { + // cgroup namespace 可以把当前组挂成根目录。深路径不存在时,仍然检查挂载根的限额。 + if membership + .components() + .any(|c| matches!(c, Component::ParentDir | Component::Prefix(_))) + { + return None; + } + let relative = membership.strip_prefix("/").unwrap_or(membership); + let current = root.join(relative); + current + .ancestors() + .take_while(|p| p.starts_with(root)) + .filter_map(|p| { + std::fs::read_to_string(p.join(file)) + .ok()? + .trim() + .parse::() + .ok() + .filter(|&n| n > 0) + }) + .min() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nested_groups_obey_the_smallest_ancestor_limit() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("service/child")).unwrap(); + std::fs::write(root.join("memory.max"), "max\n").unwrap(); + std::fs::write(root.join("service/memory.max"), "536870912\n").unwrap(); + std::fs::write(root.join("service/child/memory.max"), "1073741824\n").unwrap(); + assert_eq!( + lowest_limit(root, Path::new("/service/child"), "memory.max"), + Some(512 << 20) + ); + } + + #[test] + fn a_namespaced_mount_root_and_v1_limits_are_supported() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("memory.limit_in_bytes"), "268435456").unwrap(); + assert_eq!( + lowest_limit( + dir.path(), + Path::new("/unavailable/host/path"), + "memory.limit_in_bytes" + ), + Some(256 << 20) + ); + assert_eq!( + lowest_limit(dir.path(), Path::new("/../escape"), "memory.limit_in_bytes"), + None + ); + } +} diff --git a/crates/tw-gateway/src/server/intake.rs b/crates/tw-gateway/src/server/intake.rs index 665c1a55..03da9957 100644 --- a/crates/tw-gateway/src/server/intake.rs +++ b/crates/tw-gateway/src/server/intake.rs @@ -12,8 +12,8 @@ use axum::body::Body; use axum::http::{HeaderMap, header}; -use bytes::Bytes; -use http_body_util::{BodyExt, LengthLimitError, Limited}; +use bytes::{Bytes, BytesMut}; +use http_body_util::BodyExt; use crate::error::GatewayError; use crate::inflate::{Coding, Decode}; @@ -34,6 +34,15 @@ pub(super) async fn read( headers: &mut HeaderMap, body: Body, max: usize, +) -> Result { + read_with_budget(headers, body, max, crate::resources::body_budget()).await +} + +async fn read_with_budget( + headers: &mut HeaderMap, + mut body: Body, + max: usize, + budget: &std::sync::Arc, ) -> Result { let declared = headers .get(header::CONTENT_LENGTH) @@ -47,32 +56,55 @@ pub(super) async fn read( } // 认不得的编码在读体之前就拒:不用先收完几百兆再说不认识 let coding = coding_of(headers)?; - let raw = match Limited::new(body, max).collect().await { - Ok(c) => c.to_bytes(), - Err(e) if e.downcast_ref::().is_some() => { + let mut reservation = budget.reserve(); + let mut raw = BytesMut::new(); + while let Some(frame) = body.frame().await { + let frame = frame.map_err(|e| { + GatewayError::request(msg!( + "gw.request.body_unreadable", detail = e => + "The request body could not be read: {detail}" + )) + })?; + let Ok(data) = frame.into_data() else { + continue; + }; + let next = raw.len().saturating_add(data.len()); + if next > max { return Err(GatewayError::too_large(msg!( "gw.request.body_over_limit", max = max => "The request body is over the {max}-byte limit." ))); } - // 客户端传到一半断了。它多半已经听不到这句了,但这一行得有个结局 - Err(e) => { - return Err(GatewayError::request(msg!( - "gw.request.body_unreadable", detail = e => - "The request body could not be read: {detail}" - ))); + // 先记账再拷贝。用满就让客户端退避,不拿着半份正文等别的请求释放。 + if !reservation.grow(next) { + return Err(crate::resources::memory_busy()); } - }; + raw.extend_from_slice(&data); + } + let raw = raw.freeze(); let Some(coding) = coding else { - return Ok(raw); + return Ok(reservation.wrap(raw)); }; headers.remove(header::CONTENT_ENCODING); // 解压是纯 CPU 的活,几百兆要几百毫秒:不占 async 线程 - let decoded = tokio::task::spawn_blocking(move || coding.decode(&raw, max)) - .await - .unwrap_or_else(|e| Err(Decode::Failed(e.to_string()))); + let slot = crate::resources::heavy_slot().await; + let decoded = tokio::task::spawn_blocking(move || { + // 客户端取消时阻塞任务仍可能在跑:CPU 名额和预算都跟任务走。 + let _slot = slot; + let decoded = coding.decode_with(&raw, max, |output| { + if reservation.grow(raw.len().saturating_add(output)) { + Ok(()) + } else { + Err(Decode::Busy) + } + })?; + Ok(reservation.wrap(decoded)) + }) + .await + .unwrap_or_else(|e| Err(Decode::Failed(e.to_string()))); match decoded { Ok(b) => Ok(b), + Err(Decode::Busy) => Err(crate::resources::memory_busy()), Err(Decode::OverLimit) => Err(GatewayError::too_large(msg!( "gw.request.decoded_body_over_limit", max = max => "The request body is over the {max}-byte limit once decoded." @@ -122,6 +154,84 @@ mod tests { assert_eq!(&b[..], b"12345"); } + #[tokio::test] + async fn concurrent_bodies_share_a_budget_until_the_last_clone_is_dropped() { + let budget = crate::resources::Budget::new(30); + let body = read_with_budget(&mut HeaderMap::new(), chunked(&[b"123456"]), 100, &budget) + .await + .unwrap(); + let clone = body.clone(); + drop(body); + let e = read_with_budget(&mut HeaderMap::new(), chunked(&[b"12345"]), 100, &budget) + .await + .unwrap_err(); + assert_eq!(e.detail.code, "gw.request.memory_busy"); + assert_eq!(e.status(), axum::http::StatusCode::TOO_MANY_REQUESTS); + assert!(e.retry.is_some()); + drop(clone); + assert!( + read_with_budget(&mut HeaderMap::new(), chunked(&[b"12345"]), 100, &budget) + .await + .is_ok() + ); + } + + #[tokio::test] + async fn cancelling_a_partial_read_returns_its_budget() { + use futures::StreamExt; + let budget = crate::resources::Budget::new(30); + let stream = + futures::stream::iter([Ok::<_, std::io::Error>(Bytes::from_static(b"123456"))]) + .chain(futures::stream::pending()); + let mut headers = HeaderMap::new(); + let mut reading = Box::pin(read_with_budget( + &mut headers, + Body::from_stream(stream), + 100, + &budget, + )); + assert!( + tokio::time::timeout(std::time::Duration::from_millis(20), &mut reading) + .await + .is_err() + ); + assert!( + read_with_budget(&mut HeaderMap::new(), chunked(&[b"12345"]), 100, &budget) + .await + .is_err() + ); + drop(reading); + assert!( + read_with_budget(&mut HeaderMap::new(), chunked(&[b"12345"]), 100, &budget) + .await + .is_ok() + ); + } + + #[tokio::test] + async fn an_oversized_body_releases_its_partial_reservation() { + let budget = crate::resources::Budget::new(30); + let e = read_with_budget( + &mut HeaderMap::new(), + chunked(&[b"123456", b"789"]), + 8, + &budget, + ) + .await + .unwrap_err(); + assert_eq!(e.detail.code, "gw.request.body_over_limit"); + assert!( + read_with_budget( + &mut HeaderMap::new(), + chunked(&[b"123456789"]), + 100, + &budget + ) + .await + .is_ok() + ); + } + #[tokio::test] async fn a_body_without_a_length_stops_at_the_limit() { let e = read(&mut HeaderMap::new(), chunked(&[b"123", b"456"]), 5) @@ -170,6 +280,39 @@ mod tests { h } + #[tokio::test] + async fn decompression_reserves_output_and_releases_everything_on_failure() { + let budget = crate::resources::Budget::new(3_000); + let held = read_with_budget( + &mut HeaderMap::new(), + Body::from(vec![b'h'; 500]), + 10_000, + &budget, + ) + .await + .unwrap(); + // 压缩数据放得下,解压后的那份放不下:必须在解压增长时检查预算。 + let e = read_with_budget( + &mut with_encoding("gzip"), + Body::from(gz(&[b'x'; 1_000])), + 10_000, + &budget, + ) + .await + .unwrap_err(); + assert_eq!(e.detail.code, "gw.request.memory_busy"); + drop(held); + let decoded = read_with_budget( + &mut with_encoding("gzip"), + Body::from(gz(&[b'x'; 1_000])), + 10_000, + &budget, + ) + .await + .unwrap(); + assert_eq!(&decoded[..], &[b'x'; 1_000]); + } + #[tokio::test] async fn a_gzip_body_is_decoded_and_the_encoding_header_is_dropped() { let packed = gz(b"12345"); diff --git a/crates/tw-gateway/src/server/pipeline.rs b/crates/tw-gateway/src/server/pipeline.rs index 59f524a6..dd8742e3 100644 --- a/crates/tw-gateway/src/server/pipeline.rs +++ b/crates/tw-gateway/src/server/pipeline.rs @@ -97,7 +97,8 @@ pub(super) async fn pipeline( let parsed = serde_json::from_slice::(&req.body).ok(); let probed = probe(&state, &rt, &req, parsed.as_ref()); (parsed, probed) - }); + }) + .await; let intent = match probed { Probe::Answered(resp) => return Ok(resp), Probe::Intent(intent) => intent, @@ -107,7 +108,8 @@ pub(super) async fn pipeline( // 之后(每发往一个上游跑一次,见 `plug`),左右不了请求去哪一家 let (reading, fp) = heavy(&req.body, || { read(&req, intent, parsed.as_ref(), (state.local_time)()) - }); + }) + .await; let conv = conversation(&rt, &req, &reading, fp.as_deref()); let (choice, decision) = match route(&state, &rt, &req, &reading, conv.as_ref()) { Routed::Go(choice, decision) => (choice, decision), @@ -117,7 +119,7 @@ pub(super) async fn pipeline( Routed::Refused(choice, why) => { let to = ("", tw_api::Billing::PerToken); // 一个字节都没发出去,也没什么可报的;存下来的请求照样按这一档换、打码 - let seen = heavy(&req.body, || look(&rt, &req)); + let seen = heavy(&req.body, || look(&rt, &req)).await; let redaction = redaction(&rt, seen.ledger); let (id, _) = open( &state, @@ -267,27 +269,29 @@ async fn enter( ending, ); (screening, started) - }); + }) + .await; // 用量上限的预留跟着请求号走,等存储层记下这一行时换成实数 hold.bind(started.id); // 结论挂在请求号上报。**拒绝的也在开始之后**:被拒是一次来源为 `denied` 的失败, // 流量里照样留一行;一个字节都不发 let provider = started.alive.first().map(String::as_str).unwrap_or(""); - let refused = (!screening.hits.is_empty()) - .then(|| { - // 前后文和存下来的正文一样换、打码:同一套规则、同一本账 - let redaction = redaction(rt, started.ledger.clone()); - let src = crate::guard::detail::Screened { - body: &screened, - dialect: req.api.map(|a| a.dialect()), - rules: &rt.content, - redaction: &redaction, - }; - heavy(&screened, || { - crate::guard::report(&state.bus, started.id, provider, &screening, &src) - }) + let refused = if !screening.hits.is_empty() { + // 前后文和存下来的正文一样换、打码:同一套规则、同一本账 + let redaction = redaction(rt, started.ledger.clone()); + let src = crate::guard::detail::Screened { + body: &screened, + dialect: req.api.map(|a| a.dialect()), + rules: &rt.content, + redaction: &redaction, + }; + heavy(&screened, || { + crate::guard::report(&state.bus, started.id, provider, &screening, &src) }) - .flatten(); + .await + } else { + None + }; drop(screened); if let Some(why) = refused { return Err(GatewayError::denied(why)); @@ -1087,7 +1091,8 @@ fn start( redaction: &redacting, replaced: redact_mode.acts(), }; - let items = heavy(&req.body, || crate::guard::items(&found, 0, &seen)); + // start 已经在 heavy_for 的名额内,不能递归等同一个调度器。 + let items = crate::guard::items(&found, 0, &seen); state.bus.emit(tw_api::Event::SecretsFound { id, provider: alive.first().cloned().unwrap_or_default(), @@ -1292,30 +1297,14 @@ fn screen( sc } -/// 请求体到这么大,管线上整份解它、扫它的那几步挪出异步线程(见 [`heavy`])。 -const HEAVY_BODY: usize = 1024 * 1024; - -/// 在整个请求体上做的 CPU 活:解析、本地应答的判定、内容过滤、出站脱敏、每一跳改写请求体。 -/// -/// **大的请求体挪出异步线程做**(`block_in_place`):一个 8 MB 的请求要算几十毫秒,就地算的话, -/// 同一个线程上别的连接 —— 正在流的回答 —— 跟着停住这么久。挪出去时这个线程上排着的活交给 -/// 别的线程接着干。小的就地做:挪一次的开销比它本身还大。 -/// -/// 只在多线程的运行时上挪:单线程的运行时(测试用的就是它)里 `block_in_place` 会 panic。 -pub(super) fn heavy(body: &[u8], f: impl FnOnce() -> T) -> T { - heavy_for(body.len(), f) +/// 整份请求体的 CPU 工作统一准入;大正文或小正文的并发扫描都会按需交还 I/O 调度权。 +pub(super) async fn heavy(body: &[u8], f: impl FnOnce() -> T) -> T { + heavy_for(body.len(), f).await } -/// [`heavy`],按请求体的长度:要在 `f` 里改请求体的调用方先量好长度 -pub(super) fn heavy_for(size: usize, f: impl FnOnce() -> T) -> T { - use tokio::runtime::{Handle, RuntimeFlavor}; - let threads = - Handle::try_current().is_ok_and(|h| h.runtime_flavor() == RuntimeFlavor::MultiThread); - if size >= HEAVY_BODY && threads { - tokio::task::block_in_place(f) - } else { - f() - } +/// [`heavy`],按请求体的长度:要在 `f` 里改请求体的调用方先量好长度。 +pub(super) async fn heavy_for(size: usize, f: impl FnOnce() -> T) -> T { + crate::resources::heavy(size, f).await } /// 这个请求是 Claude Code 发的吗。 @@ -1365,3 +1354,57 @@ fn local_answer(kind: crate::clientprobe::ProbeKind, body: &Bytes) -> Response { ) .into_response() } + +#[cfg(test)] +mod scheduling_tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn heavy_work_is_bounded_while_the_async_runtime_remains_responsive() { + let cap = crate::resources::policy().heavy_jobs; + let active = Arc::new(AtomicUsize::new(0)); + let peak = Arc::new(AtomicUsize::new(0)); + let (began, mut starts) = tokio::sync::mpsc::unbounded_channel(); + let release = Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new())); + let mut jobs = Vec::new(); + for _ in 0..cap + 3 { + let (active, peak, began, release) = + (active.clone(), peak.clone(), began.clone(), release.clone()); + jobs.push(tokio::spawn(async move { + heavy_for(1024 * 1024, || { + let n = active.fetch_add(1, Ordering::SeqCst) + 1; + peak.fetch_max(n, Ordering::SeqCst); + let _ = began.send(()); + let (lock, wake) = &*release; + let guard = lock.lock().unwrap(); + // 有界等待:断言失败时测试也能收场,不会留下永久阻塞线程。 + let _guard = wake + .wait_timeout_while(guard, std::time::Duration::from_secs(5), |done| !*done) + .unwrap(); + active.fetch_sub(1, Ordering::SeqCst); + }) + .await; + })); + } + for _ in 0..cap { + tokio::time::timeout(std::time::Duration::from_secs(3), starts.recv()) + .await + .unwrap() + .unwrap(); + } + // 全部 CPU 名额被占用时,异步计时器仍能被调度,额外任务仍在异步等候。 + assert!( + tokio::time::timeout(std::time::Duration::from_millis(25), starts.recv()) + .await + .is_err() + ); + *release.0.lock().unwrap() = true; + release.1.notify_all(); + for job in jobs { + job.await.unwrap(); + } + assert_eq!(peak.load(Ordering::SeqCst), cap); + assert_eq!(active.load(Ordering::SeqCst), 0); + } +} diff --git a/crates/tw-gateway/src/server/pipeline/admission.rs b/crates/tw-gateway/src/server/pipeline/admission.rs index 1d862ddd..33541dff 100644 --- a/crates/tw-gateway/src/server/pipeline/admission.rs +++ b/crates/tw-gateway/src/server/pipeline/admission.rs @@ -55,7 +55,7 @@ pub(super) async fn admit( _ => &[], }; if let Err(r) = state.key_limits.calendar(&req.client_name, limits) { - return Err(refused(state, rt, req, reading, choice, fp, ending, &r)); + return Err(refused(state, rt, req, reading, choice, fp, ending, &r).await); } let pass = state.gate.acquire(&req.client_name, max_concurrent).await; // 等待期限从这里起算:之后的两段等待共用它 @@ -75,7 +75,7 @@ pub(super) async fn admit( hold, wait_until, }), - Err(r) => Err(refused(state, rt, req, reading, choice, fp, ending, &r)), + Err(r) => Err(refused(state, rt, req, reading, choice, fp, ending, &r).await), } } @@ -130,7 +130,7 @@ fn input_cost( /// 被上限拒了:照样开始、留一行(尝试链是空的),交回给客户端的那个 429。 #[allow(clippy::too_many_arguments)] -fn refused( +async fn refused( state: &AppState, rt: &Runtime, req: &Inbound, @@ -143,7 +143,7 @@ fn refused( tracing::info!(key = %req.client_name, per = r.limit.per.word(), "a usage limit of the key refused the request"); let why = r.error(); // 一个字节都没发出去;存下来的请求照样按这一档换、打码 - let seen = super::heavy(&req.body, || look(rt, req)); + let seen = super::heavy(&req.body, || look(rt, req)).await; let (id, _) = open( state, req, diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 4e0bb8bf..1598b930 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -637,7 +637,9 @@ pub(super) async fn try_upstreams<'a>( ); (out, effort) }) - }) { + }) + .await + { Ok(out) => out, Err(err) => { chain.push(hop_failed( @@ -689,7 +691,8 @@ pub(super) async fn try_upstreams<'a>( Some(&rt.scan_cache), ); (body, ledger, differs) - }); + }) + .await; // 用这个 provider 自己的 Client —— 它带着该走的代理。**在取密钥 // 之前拿到**:OAuth 换 token 也要走这条代理。 diff --git a/crates/tw-gateway/src/server/pipeline/plug.rs b/crates/tw-gateway/src/server/pipeline/plug.rs index 4ad3fe9d..d076f8fa 100644 --- a/crates/tw-gateway/src/server/pipeline/plug.rs +++ b/crates/tw-gateway/src/server/pipeline/plug.rs @@ -115,7 +115,10 @@ pub(super) async fn attempt( None => None, }; // 内容过滤:只报插件加进来的。处置档下删过的话,后面一律用删过的那一份 - let (body, value) = rescreen(state, rt, req, started, &provider.name, &c, reported)?; + let (body, value) = super::heavy(&c.body, || { + rescreen(state, rt, req, started, &provider.name, &c, reported) + }) + .await?; // 生成回答的请求重新解码:格式转换用改过的这一份。数 token、压缩这些不转换(只发给 // 同格式的上游),不用解 let decoded = req.api.filter(|_| reading.generates).map(|api| { diff --git a/crates/tw-guard/src/tools/net.rs b/crates/tw-guard/src/tools/net.rs index 24ca5595..281ace46 100644 --- a/crates/tw-guard/src/tools/net.rs +++ b/crates/tw-guard/src/tools/net.rs @@ -510,6 +510,22 @@ mod tests { ))); } + #[test] + fn an_outbound_uuid_is_not_by_itself_evidence_of_credential_exfiltration() { + assert!(!credentials().is_on("uuid")); + for value in [ + "550e8400-e29b-41d4-a716-446655440000", + "550e8400e29b41d4a716446655440000", + ] { + assert!( + Check::CredentialToNetwork + .find(&format!("curl https://api.example.com/orders/{value}")) + .is_none() + ); + assert!(!crate::redact::rules::scan_plain(value, &RuleSet::defaults()).is_empty()); + } + } + #[test] fn blockchain_identifiers_are_redacted_without_becoming_theft_evidence() { for value in [ diff --git a/docs/config.md b/docs/config.md index 7d355f4a..17f07674 100644 --- a/docs/config.md +++ b/docs/config.md @@ -1065,6 +1065,13 @@ Built-in rules: | `labeled-health` | Health information by field name | off | +`uuid` is on by default. It matches hexadecimal UUIDs written as 8-4-4-4-12 +or 32 consecutive hexadecimal characters, ignoring case and without restricting +the UUID version. Order and trace IDs, and compact hashes with the same shape, +are replaced too; longer tokens are not split and JSON numbers stay numbers. +Observe mode only records matches. A UUID alone does not trigger the +credential-to-network tool check; saved credentials are still checked by value. + `cn-resident-id`, `bank-card`, `email` and `cn-mobile-phone` look for personal information rather than credentials. The first two are on out of the box and match only what checks out by structure: diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index ccd4e369..ce244df6 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -815,6 +815,8 @@ pricing: | `labeled-health` | 带字段名的健康信息 | 关 | +`uuid` 出厂开启:匹配带连字符的 8-4-4-4-12 或连续 32 位十六进制 UUID,不区分大小写、不限制版本。订单号、追踪 ID 和同形的紧凑哈希也替换;更长的标识符不截取,JSON 数字仍保留为数字。监控模式只记录命中。单凭 UUID 的形状不会触发工具的「凭据发往陌生主机」检查;用户保存的凭据仍按具体值检查。 + `cn-resident-id`、`bank-card`、`email`、`cn-mobile-phone` 查找的是个人信息而不是凭据。前两条出厂开启,只认结构上核对得上的: - `cn-resident-id`:18 位的中华人民共和国居民身份证号码。前两位须是省级行政区划代码,出生日期须是 1900 年 1 月 1 日至今天之间的真实日期,末位须是正确的校验码(ISO 7064 MOD 11-2)。15 位的旧号码不认。 diff --git a/docs/server.md b/docs/server.md index 2d683de5..407b7bd5 100644 --- a/docs/server.md +++ b/docs/server.md @@ -23,6 +23,37 @@ upgrading. Every field mentioned is described in the and the version the app needs. [Upgrading](#upgrading) describes how to switch versions. +## Automatic resource scheduling + +Core sizes its runtime automatically; no `runtime` configuration or allocator +environment variables are needed. Up to eight permanent Tokio workers handle +I/O. CPU work shares slots sized from the process's available parallelism and +memory: up to one job per available CPU, limited to one per 128 MiB of memory. +An 80-core server with enough memory can run 80 CPU jobs concurrently. This is +a capacity limit, not a set of prestarted threads. Parsing, scanning, rewriting, +decompression and plugins obtain slots asynchronously before doing CPU work. +Large bodies move off the I/O scheduler immediately; concurrent small-body +scans also hand back scheduling capacity when the inline lanes are occupied. +Execution threads grow with demand, and surplus threads retire after ten idle +seconds. Plugins use the same policy with separate sandbox stacks. Streaming +responses and ordinary file or DNS operations can continue while CPU work waits. + +Incoming request bodies share a process-wide buffering budget: one eighth of +the machine's memory (the cgroup limit on Linux containers), between 64 and +512 MiB, with threefold headroom for parsing and copies. The reservation follows +the last reference to the buffered body, including while a request is queued. +When the budget is occupied, new bodies receive a retryable `429` with +`Retry-After`. A single large body can use the budget exclusively; the existing +256 MiB per-request limit still applies. This budget covers request buffering, +not the entire process RSS. + +Release binaries use mimalloc to reduce allocator fragmentation and retained +free pages. Linux builds disable transparent huge pages for the Core process +where the kernel permits it, reducing residency for small allocations without +changing system settings. The chosen worker count, heavy-work slots, buffering budget and +allocator are printed once at startup. CPU and memory sizing is calculated at +startup; execution threads grow and retire throughout the process lifetime. + ## 1. Install ```sh diff --git a/docs/server.zh-CN.md b/docs/server.zh-CN.md index 50d025eb..a44e1592 100644 --- a/docs/server.zh-CN.md +++ b/docs/server.zh-CN.md @@ -12,6 +12,16 @@ ThinkWatch Core 可以脱离桌面运行:在 Linux 机器上由 systemd 按配 - systemd。 - 服务器上运行的 core 与桌面应用内置的 core 版本相同。应用只连接控制面协议版本与自身相同的 core:它在握手时核对,版本不一致时拒绝连接,并显示双方的版本,即服务器上的版本和应用需要的版本。切换版本的方法见[升级](#升级)。 +## 自动资源调度 + +Core 自动选择运行时规模,无需添加 `runtime` 配置或分配器环境变量。最多 8 个常驻 Tokio worker 处理 I/O;CPU 任务共用按进程可用核数和内存确定的名额:最多每个可用 CPU 一个,每 128 MiB 内存允许一个。内存足够的 80 核服务器可以同时执行 80 个 CPU 任务。名额是容量上限,不会提前创建这么多线程。 + +解析、扫描、改写、解压和插件都先异步获取 CPU 名额。大正文立即交还 I/O 调度权;中小正文并发扫描、内联通道被占满时也会扩展执行线程。线程按实际负载增加,多余线程空闲 10 秒后回收;插件保留独立的沙箱栈,同样按需创建和回收线程。等待 CPU 名额时,流式回答、普通文件操作和 DNS 查询仍可继续。 + +进来的请求体共用进程级缓冲预算:取机器内存的八分之一(Linux 容器按 cgroup 限额),范围为 64 至 512 MiB,并按正文的三倍预留解析和复制的余量。预算跟随正文的最后一份引用归还,请求排队期间也计入。预算被占用时,新请求返回可重试的 `429`,带有 `Retry-After`。单个大正文可以独占预算,原有的单请求 256 MiB 上限继续适用。这是请求缓冲的预算,并非整个进程 RSS 的硬上限。 + +发布包默认使用 mimalloc,减少内存碎片和空闲页留存。Linux 构建在内核允许时对 Core 进程禁用透明大页,降低小对象分配的驻留开销,不改系统设置。启动时记录选定的 worker 数、重任务名额、正文预算和分配器。CPU 和内存上限在启动时确定,执行线程在运行期间按负载自动增加和回收。 + ## 1. 安装 ```sh diff --git a/release-notes/0.89.0.md b/release-notes/0.89.0.md new file mode 100644 index 00000000..09bd6f3d --- /dev/null +++ b/release-notes/0.89.0.md @@ -0,0 +1,7 @@ +Core now adjusts execution capacity to traffic without requiring runtime settings. A small permanent I/O scheduler handles connections while CPU execution threads grow on demand and retire after ten idle seconds. Parsing, redaction, rewriting, decompression and plugins share CPU admission sized from available parallelism and memory, allowing a sufficiently provisioned 80-core server to run 80 CPU jobs concurrently. Concurrent small-body scans can expand too. + +Release binaries use mimalloc to reduce allocation fragmentation and retained free pages. Linux builds disable transparent huge pages for the Core process where the kernel permits it, and Linux containers use their cgroup memory limits when sizing resources. Plugin sandbox threads retain their dedicated stacks and now start individually on demand and retire when idle. + +Incoming bodies share a byte budget with headroom for parsing and copies. When that budget is occupied, new requests receive a retryable `429` with `Retry-After`. Reservations remain attached to buffered data until its final reference is released, and decompression reserves space as output grows. The 256 MiB per-request limit remains in place; the buffering budget is not a hard limit on total process RSS. + +Existing configurations remain valid and no YAML changes are needed. CPU and memory ceilings are selected at startup; thread creation, admission and idle reclamation happen automatically during operation. Startup logs report the selected capacity, body budget, idle timeout and allocator. The control-plane protocol and request-store schema are unchanged.