AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
feat(grpc): implement real tonic XerjSearch server on :8081
xerj-orgd641268a6966
diff --git a/engine/Cargo.lock b/engine/Cargo.lockindex 6e30b9522..af0416d01 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -148,6 +148,28 @@ dependencies = ["syn",]+[[package]]+name = "async-stream"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"+dependencies = [+ "async-stream-impl",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-stream-impl"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "async-trait"version = "0.1.89"@@ -307,6 +329,12 @@ dependencies = ["serde",]+[[package]]+name = "beef"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"+[[package]]name = "bitflags"version = "2.11.1"@@ -790,6 +818,12 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"+[[package]]+name = "fixedbitset"+version = "0.5.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"+[[package]]name = "float-cmp"version = "0.10.0"@@ -1007,7 +1041,7 @@ dependencies = ["futures-core","futures-sink","http",- "indexmap",+ "indexmap 2.14.0","slab","tokio","tokio-util",@@ -1035,6 +1069,12 @@ dependencies = ["serde",]+[[package]]+name = "hashbrown"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"+[[package]]name = "hashbrown"version = "0.14.5"@@ -1170,6 +1210,19 @@ dependencies = ["webpki-roots",]+[[package]]+name = "hyper-timeout"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"+dependencies = [+ "hyper",+ "hyper-util",+ "pin-project-lite",+ "tokio",+ "tower-service",+]+[[package]]name = "hyper-tls"version = "0.6.0"@@ -1203,7 +1256,7 @@ dependencies = ["libc","percent-encoding","pin-project-lite",- "socket2",+ "socket2 0.6.3","system-configuration","tokio","tower-service",@@ -1344,6 +1397,16 @@ dependencies = ["icu_properties",]+[[package]]+name = "indexmap"+version = "1.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"+dependencies = [+ "autocfg",+ "hashbrown 0.12.3",+]+[[package]]name = "indexmap"version = "2.14.0"@@ -1471,6 +1534,39 @@ version = "0.4.29"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"+[[package]]+name = "logos"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7251356ef8cb7aec833ddf598c6cb24d17b689d20b993f9d11a3d764e34e6458"+dependencies = [+ "logos-derive",+]++[[package]]+name = "logos-codegen"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59f80069600c0d66734f5ff52cc42f2dabd6b29d205f333d61fd7832e9e9963f"+dependencies = [+ "beef",+ "fnv",+ "lazy_static",+ "proc-macro2",+ "quote",+ "regex-syntax",+ "syn",+]++[[package]]+name = "logos-derive"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24fb722b06a9dc12adb0963ed585f19fc61dc5413e6a9be9422ef92c091e731d"+dependencies = [+ "logos-codegen",+]+[[package]]name = "lru-slab"version = "0.1.2"@@ -1516,6 +1612,28 @@ dependencies = ["libc",]+[[package]]+name = "miette"+version = "7.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7"+dependencies = [+ "cfg-if",+ "miette-derive",+ "unicode-width",+]++[[package]]+name = "miette-derive"+version = "7.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "mime"version = "0.3.17"@@ -1556,6 +1674,12 @@ dependencies = ["version_check",]+[[package]]+name = "multimap"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"+[[package]]name = "native-tls"version = "0.2.18"@@ -1761,6 +1885,16 @@ version = "2.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[package]]+name = "petgraph"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772"+dependencies = [+ "fixedbitset",+ "indexmap 2.14.0",+]+[[package]]name = "phf"version = "0.11.3"@@ -1917,12 +2051,104 @@ dependencies = ["thiserror 1.0.69",]+[[package]]+name = "prost"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5"+dependencies = [+ "bytes",+ "prost-derive",+]++[[package]]+name = "prost-build"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf"+dependencies = [+ "heck",+ "itertools",+ "log",+ "multimap",+ "once_cell",+ "petgraph",+ "prettyplease",+ "prost",+ "prost-types",+ "regex",+ "syn",+ "tempfile",+]++[[package]]+name = "prost-derive"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"+dependencies = [+ "anyhow",+ "itertools",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "prost-reflect"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b5edd582b62f5cde844716e66d92565d7faf7ab1445c8cebce6e00fba83ddb2"+dependencies = [+ "logos",+ "miette",+ "once_cell",+ "prost",+ "prost-types",+]++[[package]]+name = "prost-types"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16"+dependencies = [+ "prost",+]+[[package]]name = "protobuf"version = "2.28.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "106dd99e98437432fed6519dedecfade6a06a73bb7b2a1e019fdd2bee5778d94"+[[package]]+name = "protox"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f352af331bf637b8ecc720f7c87bf903d2571fa2e14a66e9b2558846864b54a"+dependencies = [+ "bytes",+ "miette",+ "prost",+ "prost-reflect",+ "prost-types",+ "protox-parse",+ "thiserror 1.0.69",+]++[[package]]+name = "protox-parse"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3a462d115462c080ae000c29a47f0b3985737e5d3a995fcdbcaa5c782068dde"+dependencies = [+ "logos",+ "miette",+ "prost-types",+ "thiserror 1.0.69",+]+[[package]]name = "quinn"version = "0.11.9"@@ -1936,7 +2162,7 @@ dependencies = ["quinn-udp","rustc-hash","rustls",- "socket2",+ "socket2 0.6.3","thiserror 2.0.18","tokio","tracing",@@ -1973,7 +2199,7 @@ dependencies = ["cfg_aliases","libc","once_cell",- "socket2",+ "socket2 0.6.3","tracing","windows-sys 0.52.0",]@@ -2457,7 +2683,7 @@ version = "0.9.34+deprecated"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"dependencies = [- "indexmap",+ "indexmap 2.14.0","itoa","ryu","serde",@@ -2539,6 +2765,16 @@ version = "1.15.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"+[[package]]+name = "socket2"+version = "0.5.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"+dependencies = [+ "libc",+ "windows-sys 0.52.0",+]+[[package]]name = "socket2"version = "0.6.3"@@ -2785,7 +3021,7 @@ dependencies = ["parking_lot","pin-project-lite","signal-hook-registry",- "socket2",+ "socket2 0.6.3","tokio-macros","windows-sys 0.61.2",]@@ -2821,6 +3057,17 @@ dependencies = ["tokio",]+[[package]]+name = "tokio-stream"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+]+[[package]]name = "tokio-util"version = "0.7.18"@@ -2861,7 +3108,7 @@ version = "0.22.27"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"dependencies = [- "indexmap",+ "indexmap 2.14.0","serde","serde_spanned","toml_datetime",@@ -2875,6 +3122,50 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"+[[package]]+name = "tonic"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877c5b330756d856ffcc4553ab34a5684481ade925ecc54bcd1bf02b1d0d4d52"+dependencies = [+ "async-stream",+ "async-trait",+ "axum",+ "base64 0.22.1",+ "bytes",+ "h2",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-timeout",+ "hyper-util",+ "percent-encoding",+ "pin-project",+ "prost",+ "socket2 0.5.10",+ "tokio",+ "tokio-stream",+ "tower 0.4.13",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "tonic-build"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9557ce109ea773b399c9b9e5dca39294110b74f1f342cb347a80d1fce8c26a11"+dependencies = [+ "prettyplease",+ "proc-macro2",+ "prost-build",+ "prost-types",+ "quote",+ "syn",+]+[[package]]name = "tower"version = "0.4.13"@@ -2883,8 +3174,13 @@ checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"dependencies = ["futures-core","futures-util",+ "indexmap 1.9.3","pin-project","pin-project-lite",+ "rand 0.8.5",+ "slab",+ "tokio",+ "tokio-util","tower-layer","tower-service","tracing",@@ -3067,6 +3363,12 @@ version = "1.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"+[[package]]+name = "unicode-width"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"+[[package]]name = "unicode-xid"version = "0.2.6"@@ -3267,7 +3569,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"dependencies = ["anyhow",- "indexmap",+ "indexmap 2.14.0","wasm-encoder","wasmparser",]@@ -3280,7 +3582,7 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"dependencies = ["bitflags","hashbrown 0.15.5",- "indexmap",+ "indexmap 2.14.0","semver",]@@ -3579,7 +3881,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"dependencies = ["anyhow","heck",- "indexmap",+ "indexmap 2.14.0","prettyplease","syn","wasm-metadata",@@ -3610,7 +3912,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"dependencies = ["anyhow","bitflags",- "indexmap",+ "indexmap 2.14.0","log","serde","serde_derive",@@ -3629,7 +3931,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"dependencies = ["anyhow","id-arena",- "indexmap",+ "indexmap 2.14.0","log","semver","serde",@@ -3901,6 +4203,8 @@ dependencies = ["chrono","memchr","memmap2",+ "prost",+ "protox","rand 0.8.5","rayon","rcgen",@@ -3911,6 +4215,8 @@ dependencies = ["tempfile","tikv-jemallocator","tokio",+ "tonic",+ "tonic-build","tracing","tracing-subscriber","xerj-ai",@@ -3922,6 +4228,7 @@ dependencies = ["xerj-engine","xerj-fts","xerj-logs",+ "xerj-query","xerj-storage","xerj-vector",]diff --git a/engine/Cargo.toml b/engine/Cargo.tomlindex 17a0bc6ca..1993fc4f0 100644--- a/engine/Cargo.toml+++ b/engine/Cargo.toml@@ -80,6 +80,19 @@ rustls = "0.23"rcgen = "0.13"# Metricsprometheus = "0.13"+# gRPC (XerjSearch service on :8081). Default features only — the `tls`+# feature is intentionally OFF so tonic pulls no crypto backend (no+# aws-lc-rs / vendored OpenSSL); the gRPC listener speaks plaintext h2c,+# while the REST/ES listeners keep terminating TLS via axum-server+ring.+tonic = { version = "0.12", default-features = false, features = ["channel", "codegen", "prost", "router", "server"] }+prost = "0.13"+# Build-time codegen. `protox` is a PURE-RUST protobuf compiler, so the+# build needs NO `protoc` binary on the host — critical for the+# cross-compile matrix (musl/aarch64/windows/macos) where a host protoc+# is not guaranteed. It emits a FileDescriptorSet that tonic-build turns+# into Rust via `compile_fds` (never shelling out to protoc).+tonic-build = { version = "0.12", default-features = false, features = ["prost", "transport"] }+protox = "0.7"# HTTP client (for embedding proxy)reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "http2", "charset"] }# Testingdiff --git a/engine/crates/xerj-server/Cargo.toml b/engine/crates/xerj-server/Cargo.tomlindex a2c5e540b..bb1ac7262 100644--- a/engine/crates/xerj-server/Cargo.toml+++ b/engine/crates/xerj-server/Cargo.toml@@ -13,6 +13,7 @@ path = "src/main.rs"[dependencies]xerj-common = { path = "../xerj-common" }xerj-engine = { path = "../xerj-engine" }+xerj-query = { path = "../xerj-query" }xerj-api = { path = "../xerj-api" }xerj-storage = { path = "../xerj-storage" }xerj-fts = { path = "../xerj-fts" }@@ -45,6 +46,10 @@ memmap2 = { workspace = true }memchr = { workspace = true }rayon = { workspace = true }+# gRPC server: the real XerjSearch service on :8081 (proto: ../../proto/xerj.proto).+tonic.workspace = true+prost.workspace = true+# Use jemalloc as the global allocator. The default glibc malloc causes# pathological memory retention under heavy churn (ingest → flush → ingest)# because it never returns freed heap pages to the OS. jemalloc is@@ -53,6 +58,13 @@ rayon = { workspace = true }[target.'cfg(not(target_env = "msvc"))'.dependencies]tikv-jemallocator = "0.6"+[build-dependencies]+# Compile ../../proto/xerj.proto → Rust at build time. `protox` parses the+# .proto in pure Rust (no host protoc); `tonic-build` turns the resulting+# FileDescriptorSet into the client + server stubs via `compile_fds`.+tonic-build = { workspace = true }+protox = { workspace = true }+[dev-dependencies]# HTTPS round-trip test against the in-process rustls listener.reqwest = { workspace = true }diff --git a/engine/crates/xerj-server/build.rs b/engine/crates/xerj-server/build.rsnew file mode 100644index 000000000..7a98ec19f--- /dev/null+++ b/engine/crates/xerj-server/build.rs@@ -0,0 +1,33 @@+//! Build script: compile `proto/xerj.proto` into Rust gRPC stubs.+//!+//! We deliberately do NOT depend on a host `protoc` binary. `protox` is a+//! pure-Rust protobuf compiler that parses the `.proto` file and produces a+//! `FileDescriptorSet`, which `tonic-build` then turns into the prost message+//! types plus the `XerjSearch` client/server stubs via `compile_fds`. This+//! keeps the build hermetic and portable across the whole cross-compile+//! matrix (musl / aarch64 / windows / macos) where `protoc` is not+//! guaranteed to be installed.++use std::path::PathBuf;++fn main() -> Result<(), Box<dyn std::error::Error>> {+ let proto_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join("..")+ .join("..")+ .join("proto");+ let proto_file = proto_root.join("xerj.proto");++ println!("cargo:rerun-if-changed={}", proto_file.display());+ println!("cargo:rerun-if-changed=build.rs");++ // Pure-Rust parse → FileDescriptorSet (no `protoc` process spawned).+ let file_descriptors = protox::compile([&proto_file], [&proto_root])?;++ // FileDescriptorSet → Rust (messages + XerjSearch client & server).+ tonic_build::configure()+ .build_client(true)+ .build_server(true)+ .compile_fds(file_descriptors)?;++ Ok(())+}diff --git a/engine/crates/xerj-server/src/grpc.rs b/engine/crates/xerj-server/src/grpc.rsnew file mode 100644index 000000000..093714d76--- /dev/null+++ b/engine/crates/xerj-server/src/grpc.rs@@ -0,0 +1,411 @@+//! Real tonic gRPC server for the `XerjSearch` service (default `:8081`).+//!+//! Replaces the v0.1 placeholder (which only bound the port and dropped+//! connections). The service is a thin adapter over the same `Engine`/`Index`+//! methods the REST and ES-compat listeners use, so gRPC clients get identical+//! semantics. Wire schema: `proto/xerj.proto` (package `xerj.v1`), compiled to+//! Rust by `build.rs` (pure-Rust `protox`, no host `protoc`).+//!+//! The listener speaks plaintext HTTP/2 (h2c). TLS termination stays with the+//! REST/ES listeners (axum-server + ring); tonic is built without its `tls`+//! feature so no second crypto backend is dragged in.++use std::net::SocketAddr;++use anyhow::Context;+use tonic::{Request, Response, Status, Streaming};+use tracing::info;++use xerj_api::AppState;+use xerj_query::parse_request;++/// Generated prost messages + tonic client/server stubs for `xerj.v1`.+///+/// The generated code is exempted from lints — it is machine-emitted and not+/// meant to satisfy this crate's `-D warnings` clippy gate.+#[allow(clippy::all, clippy::pedantic, clippy::nursery, missing_docs)]+pub mod pb {+ tonic::include_proto!("xerj.v1");+}++use pb::xerj_search_server::{XerjSearch, XerjSearchServer};++/// gRPC adapter over the engine. Clone is cheap — `AppState` is all `Arc`s.+#[derive(Clone)]+pub struct GrpcService {+ state: AppState,+}++impl GrpcService {+ /// Build the service from shared server state.+ pub fn new(state: AppState) -> Self {+ Self { state }+ }+}++#[tonic::async_trait]+impl XerjSearch for GrpcService {+ async fn search(+ &self,+ request: Request<pb::SearchRequest>,+ ) -> Result<Response<pb::SearchResponse>, Status> {+ let req = request.into_inner();++ let idx = self+ .state+ .engine+ .get_index(&req.index)+ .map_err(|e| Status::not_found(e.to_string()))?;++ // `query_json` is the ES query DSL. We accept both a bare query clause+ // (e.g. `{"match":{...}}`) and a full request body (`{"query":{...},+ // "size":...}`); an empty string means match_all. The dedicated+ // `size`/`from` fields override the body when set (non-zero).+ let mut body: serde_json::Value = if req.query_json.trim().is_empty() {+ serde_json::json!({ "query": { "match_all": {} } })+ } else {+ serde_json::from_str(&req.query_json).map_err(|e| {+ Status::invalid_argument(format!("query_json is not valid JSON: {e}"))+ })?+ };+ if body.get("query").is_none() {+ body = serde_json::json!({ "query": body });+ }+ if req.size != 0 {+ body["size"] = serde_json::json!(req.size);+ }+ if req.from != 0 {+ body["from"] = serde_json::json!(req.from);+ }++ let search_req = parse_request(&body)+ .map_err(|e| Status::invalid_argument(format!("invalid query: {e}")))?;++ let started = std::time::Instant::now();+ let result = idx+ .search(&search_req)+ .await+ .map_err(|e| Status::internal(e.to_string()))?;+ let took_ms = started.elapsed().as_millis() as i64;++ let hits = result+ .hits+ .iter()+ .map(|h| pb::Hit {+ id: h.id.clone(),+ score: h.score,+ source_json: h.source.to_string(),+ index: req.index.clone(),+ })+ .collect();++ Ok(Response::new(pb::SearchResponse {+ total_hits: result.total.value as i64,+ hits,+ took_ms,+ timed_out: result.timed_out,+ }))+ }++ async fn index(+ &self,+ request: Request<pb::IndexRequest>,+ ) -> Result<Response<pb::IndexResponse>, Status> {+ let req = request.into_inner();++ // Index-on-write: ES auto-creates the index on first document.+ let idx = self+ .state+ .engine+ .get_or_create_index(&req.index)+ .map_err(|e| Status::invalid_argument(e.to_string()))?;++ let source: serde_json::Value = serde_json::from_str(&req.source_json)+ .map_err(|e| Status::invalid_argument(format!("source_json is not valid JSON: {e}")))?;++ let id = if req.id.is_empty() {+ None+ } else {+ Some(req.id.clone())+ };++ let resp = idx+ .index_document(id, source)+ .await+ .map_err(|e| Status::internal(e.to_string()))?;+ self.state.metrics.record_doc_indexed(&req.index);++ Ok(Response::new(pb::IndexResponse {+ id: resp.id,+ version: resp.version as i64,+ result: resp.result,+ }))+ }++ async fn bulk_index(+ &self,+ request: Request<Streaming<pb::IndexRequest>>,+ ) -> Result<Response<pb::BulkResponse>, Status> {+ let mut stream = request.into_inner();+ let started = std::time::Instant::now();+ let mut indexed = 0i32;+ let mut errors = false;++ while let Some(item) = stream.message().await? {+ let idx = match self.state.engine.get_or_create_index(&item.index) {+ Ok(i) => i,+ Err(_) => {+ errors = true;+ continue;+ }+ };+ let source: serde_json::Value = match serde_json::from_str(&item.source_json) {+ Ok(v) => v,+ Err(_) => {+ errors = true;+ continue;+ }+ };+ let id = if item.id.is_empty() {+ None+ } else {+ Some(item.id)+ };+ if idx.index_document(id, source).await.is_ok() {+ indexed += 1;+ self.state.metrics.record_doc_indexed(&item.index);+ } else {+ errors = true;+ }+ }++ Ok(Response::new(pb::BulkResponse {+ took_ms: started.elapsed().as_millis() as i64,+ errors,+ indexed,+ }))+ }++ async fn get_document(+ &self,+ request: Request<pb::GetRequest>,+ ) -> Result<Response<pb::GetResponse>, Status> {+ let req = request.into_inner();++ // Unknown index → "not found" (ES GET semantics), not an error.+ let idx = match self.state.engine.get_index(&req.index) {+ Ok(i) => i,+ Err(_) => {+ return Ok(Response::new(pb::GetResponse {+ found: false,+ id: req.id,+ source_json: String::new(),+ version: 0,+ }));+ }+ };++ match idx+ .get_document(&req.id)+ .await+ .map_err(|e| Status::internal(e.to_string()))?+ {+ Some(source) => Ok(Response::new(pb::GetResponse {+ found: true,+ id: req.id,+ source_json: source.to_string(),+ version: 1,+ })),+ None => Ok(Response::new(pb::GetResponse {+ found: false,+ id: req.id,+ source_json: String::new(),+ version: 0,+ })),+ }+ }++ async fn delete_document(+ &self,+ request: Request<pb::DeleteRequest>,+ ) -> Result<Response<pb::DeleteResponse>, Status> {+ let req = request.into_inner();++ let idx = self+ .state+ .engine+ .get_index(&req.index)+ .map_err(|e| Status::not_found(e.to_string()))?;++ let existed = idx+ .delete_document(&req.id)+ .await+ .map_err(|e| Status::internal(e.to_string()))?;++ Ok(Response::new(pb::DeleteResponse {+ result: if existed { "deleted" } else { "not_found" }.to_string(),+ }))+ }++ async fn health(+ &self,+ _request: Request<pb::HealthRequest>,+ ) -> Result<Response<pb::HealthResponse>, Status> {+ let health = self.state.engine.health().await;+ Ok(Response::new(pb::HealthResponse {+ status: health.status,+ num_indices: health.index_count as i32,+ total_docs: health.total_docs as i64,+ }))+ }+}++/// Serve the `XerjSearch` gRPC service on `addr` until `shutdown` resolves.+///+/// Returns `Err` if the port cannot be bound or the transport fails; callers+/// log-and-continue so a gRPC bind failure never takes the whole server down.+pub async fn serve_grpc<F>(addr: SocketAddr, state: AppState, shutdown: F) -> anyhow::Result<()>+where+ F: std::future::Future<Output = ()> + Send + 'static,+{+ let svc = XerjSearchServer::new(GrpcService::new(state));+ info!("gRPC XerjSearch listening on {addr}");+ tonic::transport::Server::builder()+ .add_service(svc)+ .serve_with_shutdown(addr, shutdown)+ .await+ .context("gRPC transport error")?;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::pb::xerj_search_client::XerjSearchClient;+ use super::*;+ use tempfile::TempDir;+ use xerj_common::config::Config;+ use xerj_common::metrics::Metrics;+ use xerj_engine::Engine;++ fn app_state(dir: &TempDir) -> AppState {+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_str().unwrap().to_string();+ let metrics = Metrics::new().expect("metrics init");+ let engine = Engine::new(config.clone()).expect("engine init");+ AppState::new(config, engine, metrics)+ }++ /// Grab an ephemeral port by binding then dropping a std listener.+ fn free_port() -> u16 {+ std::net::TcpListener::bind("127.0.0.1:0")+ .unwrap()+ .local_addr()+ .unwrap()+ .port()+ }++ async fn connect(addr: &str) -> XerjSearchClient<tonic::transport::Channel> {+ // The server task needs a moment to start listening; retry briefly.+ for _ in 0..50 {+ if let Ok(c) = XerjSearchClient::connect(addr.to_string()).await {+ return c;+ }+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;+ }+ panic!("gRPC client could not connect to {addr}");+ }++ #[tokio::test]+ async fn grpc_health_index_get_search_roundtrip() {+ let dir = TempDir::new().unwrap();+ let state = app_state(&dir);++ let port = free_port();+ let addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();+ let (tx, rx) = tokio::sync::oneshot::channel::<()>();++ let server = tokio::spawn(serve_grpc(addr, state, async move {+ let _ = rx.await;+ }));++ let url = format!("http://127.0.0.1:{port}");+ let mut client = connect(&url).await;++ // ── Health ───────────────────────────────────────────────────────+ let health = client+ .health(pb::HealthRequest {})+ .await+ .expect("health rpc")+ .into_inner();+ assert!(!health.status.is_empty(), "health status must be set");++ // ── Index → GetDocument round-trip ───────────────────────────────+ let indexed = client+ .index(pb::IndexRequest {+ index: "grpc_test".into(),+ id: "doc1".into(),+ source_json: r#"{"title":"hello grpc","n":7}"#.into(),+ })+ .await+ .expect("index rpc")+ .into_inner();+ assert_eq!(indexed.id, "doc1");+ assert_eq!(indexed.result, "created");++ let got = client+ .get_document(pb::GetRequest {+ index: "grpc_test".into(),+ id: "doc1".into(),+ })+ .await+ .expect("get rpc")+ .into_inner();+ assert!(got.found, "indexed document must be found");+ let source: serde_json::Value = serde_json::from_str(&got.source_json).unwrap();+ assert_eq!(source["title"], "hello grpc");++ // A missing document must report not-found, not error.+ let missing = client+ .get_document(pb::GetRequest {+ index: "grpc_test".into(),+ id: "nope".into(),+ })+ .await+ .expect("get rpc (missing)")+ .into_inner();+ assert!(!missing.found);++ // ── Search must see the freshly indexed (memtable) doc ───────────+ let search = client+ .search(pb::SearchRequest {+ index: "grpc_test".into(),+ query_json: r#"{"match":{"title":"hello"}}"#.into(),+ size: 10,+ from: 0,+ })+ .await+ .expect("search rpc")+ .into_inner();+ assert!(+ search.total_hits >= 1,+ "search should match the indexed doc, got {}",+ search.total_hits+ );+ assert_eq!(search.hits.first().map(|h| h.id.as_str()), Some("doc1"));++ // ── Delete ───────────────────────────────────────────────────────+ let deleted = client+ .delete_document(pb::DeleteRequest {+ index: "grpc_test".into(),+ id: "doc1".into(),+ })+ .await+ .expect("delete rpc")+ .into_inner();+ assert_eq!(deleted.result, "deleted");++ // Shut the server down cleanly.+ let _ = tx.send(());+ let _ = server.await;+ }+}diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 462031077..1fed58ce7 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -6,7 +6,7 @@//!//! - Native REST — default :8080//! - ES-compat — default :9200-//! - gRPC — default :8081 (placeholder in v0.1)+//! - gRPC — default :8081 (XerjSearch service, plaintext h2c)//!//! Shuts down gracefully on SIGTERM or SIGINT.//!@@ -48,6 +48,8 @@ use xerj_common::{config::Config, metrics::Metrics};use xerj_console_api::{state::ClusterMode, ConsoleState};use xerj_engine::Engine;+mod grpc;+// ─────────────────────────────────────────────────────────────────────────────// CLI// ─────────────────────────────────────────────────────────────────────────────@@ -136,7 +138,7 @@ fn print_banner(cfg: &Config, startup_ms: u128) {println!();println!(" Native REST :{} [{}]", cfg.server.rest_port, tls);println!(" ES-compat :{} [{}]", cfg.server.es_compat_port, tls);- println!(" gRPC :{} [placeholder]", cfg.server.grpc_port);+ println!(" gRPC :{} [h2c]", cfg.server.grpc_port);println!(" Data dir {}", cfg.server.data_dir);println!(" Started in {}ms", startup_ms);println!();@@ -419,39 +421,6 @@ async fn serve(Ok(())}-/// gRPC is a placeholder in v0.1 — binds the port and immediately closes-/// connections so clients receive a clean "connection refused" alternative-/// rather than no response.-async fn serve_grpc_placeholder(addr: SocketAddr) {- match TcpListener::bind(addr).await {- Ok(listener) => {- info!("gRPC placeholder bound on {addr} (not yet implemented)");- // The placeholder exits on the same SIGTERM/SIGINT signals that- // shut the REST listeners down — without this, the accept loop- // is infinite and the parent `tokio::join!(rest, es, grpc)` in- // main never returns, so the engine's `flush_all_force` shutdown- // hook never runs. Caught by the durability bench at- // 2026-04-25 (regression alongside B-2b's flush hook).- loop {- tokio::select! {- accepted = listener.accept() => match accepted {- Ok(_conn) => {} // drop immediately- Err(e) => {- warn!("gRPC placeholder accept error: {e}");- tokio::time::sleep(std::time::Duration::from_millis(100)).await;- }- },- _ = shutdown_signal() => {- info!("gRPC placeholder shut down cleanly");- return;- }- }- }- }- Err(e) => warn!("gRPC placeholder: could not bind {addr}: {e}"),- }-}-// ─────────────────────────────────────────────────────────────────────────────// Main// ─────────────────────────────────────────────────────────────────────────────@@ -1113,8 +1082,14 @@ async fn async_main() -> Result<()> {}});+ // Real tonic XerjSearch service. Exits on the same SIGTERM/SIGINT as the+ // REST listeners so `tokio::join!` below returns and the shutdown flush+ // hook runs. A bind/transport failure is logged, not fatal.+ let grpc_state = state.clone();let grpc = tokio::spawn(async move {- serve_grpc_placeholder(grpc_addr).await;+ if let Err(e) = grpc::serve_grpc(grpc_addr, grpc_state, shutdown_signal()).await {+ error!("gRPC server: {e:#}");+ }});// 14. Wait for all servers (they exit together on shutdown)