Skip to main content

reddb_server/
grpc.rs

1pub(crate) use crate::application::json_input::{
2    json_bool_field, json_f32_field, json_string_field, json_usize_field,
3};
4pub(crate) use crate::application::{
5    AdminUseCases, CreateEdgeInput, CreateEntityOutput, CreateNodeGraphLinkInput, CreateNodeInput,
6    CreateNodeTableLinkInput, CreateRowInput, CreateVectorInput, DeleteEntityInput, EntityUseCases,
7    ExplainQueryInput, GraphCentralityInput, GraphClusteringInput, GraphCommunitiesInput,
8    GraphComponentsInput, GraphCyclesInput, GraphHitsInput, GraphNeighborhoodInput,
9    GraphPersonalizedPageRankInput, GraphShortestPathInput, GraphTopologicalSortInput,
10    GraphTraversalInput, GraphUseCases, InspectNativeArtifactInput, NativeUseCases,
11    PatchEntityInput, SearchHybridInput, SearchIvfInput, SearchSimilarInput, SearchTextInput,
12};
13use std::collections::BTreeMap;
14use std::pin::Pin;
15use std::sync::Arc;
16use std::time::{SystemTime, UNIX_EPOCH};
17
18use crate::api::{RedDBOptions, RedDBResult};
19use crate::auth::middleware::{check_permission, AuthResult, AuthSource};
20use crate::auth::store::AuthStore;
21use crate::auth::Role;
22use crate::health::{HealthProvider, HealthState};
23use crate::json::{
24    from_str as json_from_str, to_string as json_to_string, Map, Value as JsonValue,
25};
26use crate::runtime::query_request::{
27    ParamValue, PreparedId, PreparedRegistry, QueryRequest as RuntimeQueryRequest,
28    QueryRequestExecutor,
29};
30use crate::runtime::{
31    RedDBRuntime, RuntimeFilter, RuntimeFilterValue, RuntimeGraphCentralityAlgorithm,
32    RuntimeGraphCentralityResult, RuntimeGraphClusteringResult, RuntimeGraphCommunityAlgorithm,
33    RuntimeGraphCommunityResult, RuntimeGraphComponentsMode, RuntimeGraphComponentsResult,
34    RuntimeGraphCyclesResult, RuntimeGraphDirection, RuntimeGraphHitsResult,
35    RuntimeGraphNeighborhoodResult, RuntimeGraphPathAlgorithm, RuntimeGraphPathResult,
36    RuntimeGraphPattern, RuntimeGraphProjection, RuntimeGraphTopologicalSortResult,
37    RuntimeGraphTraversalResult, RuntimeGraphTraversalStrategy, RuntimeIvfSearchResult,
38    RuntimeQueryResult, RuntimeQueryWeights, RuntimeStats, ScanPage,
39};
40use crate::storage::unified::devx::refs::{NodeRef, TableRef};
41use crate::storage::unified::{Metadata, MetadataValue};
42use crate::storage::{EntityData, EntityId, UnifiedEntity};
43use prost::Message;
44use reddb_types::Value;
45use tokio_stream::wrappers::TcpListenerStream;
46use tonic::metadata::MetadataMap;
47use tonic::{Request, Response, Status};
48
49// gRPC protobuf types and tonic stubs live in the standalone
50// `reddb-grpc-proto` crate so `reddb-server` and `reddb-client`
51// can both consume them without a dependency cycle. We expose
52// them under the legacy `proto` module path so existing
53// `crate::grpc::proto::…` imports keep resolving.
54pub use reddb_grpc_proto as proto;
55
56use proto::red_db_server::{RedDb, RedDbServer};
57use proto::{
58    ask_stream_event, AskAnswerToken, AskReply, AskRequest, AskSources, AskStreamEvent,
59    BatchInsertChunk, BatchInsertReply, BatchQueryReply, BatchQueryRequest, BulkEntityReply,
60    Citation, CollectionRequest, CollectionsReply, DeleteEntityRequest, DeploymentProfileRequest,
61    Empty, EntityReply, ExecutePreparedRequest, ExportRequest, GraphProjectionUpsertRequest,
62    HealthReply, IndexNameRequest, IndexToggleRequest, JsonBulkCreateRequest, JsonCreateRequest,
63    JsonPayloadRequest, KvWatchEvent, KvWatchRequest, ManifestRequest, OperationReply,
64    PayloadReply, PrepareQueryReply, PrepareQueryRequest, QueryReply, QueryRequest, QueryValue,
65    ScanEntity, ScanReply, ScanRequest, StatsReply, TopologyReply, TopologyRequest,
66    TypedCreateRowRequest, UpdateEntityRequest, Validation, ValidationItem,
67    WalCatchup as GrpcWalCatchup, WalStreamChunk as GrpcWalStreamChunk,
68    WalStreamRecord as GrpcWalStreamRecord, WalStreamRequest as GrpcWalStreamRequest,
69};
70
71pub(crate) mod catalog_dispatch;
72pub(crate) mod control_support;
73mod entity_ops;
74mod input_support;
75pub(crate) mod scan_json;
76
77use self::catalog_dispatch::*;
78use self::control_support::*;
79use self::entity_ops::*;
80use self::input_support::*;
81use self::scan_json::*;
82
83#[derive(Debug, Clone)]
84pub struct GrpcServerOptions {
85    pub bind_addr: String,
86    /// Optional TLS configuration. When set the server terminates
87    /// TLS for inbound gRPC traffic via `tonic::transport::ServerTlsConfig`.
88    /// When `None`, the listener stays plaintext (back-compat for
89    /// loopback / sidecar deployments where a sidecar terminates TLS).
90    pub tls: Option<GrpcTlsOptions>,
91}
92
93/// PEM-encoded TLS material for gRPC's tonic-rustls server.
94///
95/// The server identity is required (cert + key); the optional
96/// client-CA enables mTLS — when present, tonic verifies and
97/// requires a client cert chain that anchors at this CA bundle.
98#[derive(Debug, Clone)]
99pub struct GrpcTlsOptions {
100    /// PEM bytes for the server certificate chain (leaf first).
101    pub cert_pem: Vec<u8>,
102    /// PEM bytes for the server private key (PKCS#8 / SEC1 / RSA).
103    pub key_pem: Vec<u8>,
104    /// Optional PEM bytes for the trust anchor used to verify
105    /// client certificates. When `Some(_)`, the server requires
106    /// every client to present a cert that chains to this CA;
107    /// when `None`, the server runs one-way TLS only.
108    pub client_ca_pem: Option<Vec<u8>>,
109}
110
111impl GrpcTlsOptions {
112    /// Build a `tonic` `ServerTlsConfig` from PEM bytes, applying
113    /// rustls defaults (TLS 1.2 + 1.3 — older versions are not
114    /// negotiable on tokio-rustls 0.26).
115    pub fn to_tonic_config(
116        &self,
117    ) -> Result<tonic::transport::ServerTlsConfig, Box<dyn std::error::Error>> {
118        // With both providers linked, tonic cannot infer a default for a
119        // gRPC-only process. Keep its existing ring default unless an embedder
120        // already installed a provider.
121        #[cfg(feature = "http-tls-pq")]
122        let _ = rustls::crypto::ring::default_provider().install_default();
123
124        let identity = tonic::transport::Identity::from_pem(&self.cert_pem, &self.key_pem);
125        let mut cfg = tonic::transport::ServerTlsConfig::new().identity(identity);
126        if let Some(ca_pem) = &self.client_ca_pem {
127            cfg = cfg.client_ca_root(tonic::transport::Certificate::from_pem(ca_pem));
128        }
129        Ok(cfg)
130    }
131}
132
133/// Per-connection ceiling on concurrent HTTP/2 streams. tonic's default is
134/// unbounded, so one connection could open arbitrarily many RPCs.
135const GRPC_MAX_CONCURRENT_STREAMS: u32 = 256;
136
137/// Ceiling on concurrent in-flight requests per connection, mirroring the
138/// HTTP edge's in-flight cap.
139const GRPC_CONCURRENCY_LIMIT_PER_CONNECTION: usize = 256;
140
141/// Keepalive ping cadence and reply grace. Without these a half-open
142/// connection is only reclaimed when the OS notices.
143const GRPC_KEEPALIVE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
144const GRPC_KEEPALIVE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
145
146/// The gRPC listener had no timeouts and no concurrency ceiling: a peer could
147/// open a connection, never finish a request, and hold server resources
148/// indefinitely, or open unbounded concurrent streams on one connection.
149/// Every `serve*` entry point builds through here so the three of them cannot
150/// drift apart.
151fn configured_transport_builder() -> tonic::transport::Server {
152    tonic::transport::Server::builder()
153        .max_concurrent_streams(Some(GRPC_MAX_CONCURRENT_STREAMS))
154        .concurrency_limit_per_connection(GRPC_CONCURRENCY_LIMIT_PER_CONNECTION)
155        .http2_keepalive_interval(Some(GRPC_KEEPALIVE_INTERVAL))
156        .http2_keepalive_timeout(Some(GRPC_KEEPALIVE_TIMEOUT))
157}
158
159impl Default for GrpcServerOptions {
160    fn default() -> Self {
161        Self {
162            bind_addr: "127.0.0.1:55055".to_string(),
163            tls: None,
164        }
165    }
166}
167
168#[derive(Clone)]
169pub struct RedDBGrpcServer {
170    runtime: RedDBRuntime,
171    options: GrpcServerOptions,
172    auth_store: Arc<AuthStore>,
173    prepared_registry: Arc<PreparedRegistry>,
174    /// Optional OAuth/OIDC JWT validator. When set, the gRPC
175    /// interceptor validates JWT-shaped bearers against the issuer's
176    /// JWKS *before* attempting `AuthStore` session/api-key lookups.
177    /// Build externally via `crate::auth::OAuthValidator::with_verifier`
178    /// and attach with [`Self::with_oauth_validator`].
179    oauth_validator: Option<Arc<crate::auth::OAuthValidator>>,
180}
181
182impl RedDBGrpcServer {
183    pub fn new(runtime: RedDBRuntime) -> Self {
184        let auth_config = crate::auth::AuthConfig::default();
185        let auth_store = Arc::new(AuthStore::new(auth_config));
186        Self::with_options(runtime, GrpcServerOptions::default(), auth_store)
187    }
188
189    pub fn from_database_options(
190        db_options: RedDBOptions,
191        options: GrpcServerOptions,
192    ) -> RedDBResult<Self> {
193        // Create runtime first so we can access the pager for vault pages.
194        let runtime = RedDBRuntime::with_options(db_options.clone())?;
195
196        let auth_store = if db_options.auth.vault_enabled {
197            // The vault stores its encrypted state in reserved pages inside
198            // the main .rdb file.  Extract the pager reference from the
199            // runtime's underlying store.
200            let pager = runtime.db().store().pager().cloned().ok_or_else(|| {
201                crate::api::RedDBError::Internal(
202                    "vault requires a paged database (persistent mode)".into(),
203                )
204            })?;
205            let store = AuthStore::with_vault(db_options.auth.clone(), pager)
206                .map_err(|e| crate::api::RedDBError::Internal(e.to_string()))?;
207            Arc::new(store)
208        } else {
209            Arc::new(AuthStore::new(db_options.auth.clone()))
210        };
211        auth_store.bootstrap_from_env();
212        Ok(Self::with_options(runtime, options, auth_store))
213    }
214
215    pub fn with_options(
216        runtime: RedDBRuntime,
217        options: GrpcServerOptions,
218        auth_store: Arc<AuthStore>,
219    ) -> Self {
220        // Inject the auth store into the runtime so that Value::Secret
221        // auto-encrypt/decrypt can read the vault AES key.
222        runtime.set_auth_store(Arc::clone(&auth_store));
223        Self {
224            runtime,
225            options,
226            auth_store,
227            prepared_registry: Arc::new(PreparedRegistry::new()),
228            oauth_validator: None,
229        }
230    }
231
232    /// Attach an externally-constructed OAuth/OIDC JWT validator. Once
233    /// set, JWT-shaped bearer tokens (3-segment) on the
234    /// `authorization` metadata are validated against the issuer's
235    /// JWKS, expiry, audience, etc. Non-JWT bearers fall back to the
236    /// `AuthStore` session/API-key path.
237    pub fn with_oauth_validator(mut self, validator: Arc<crate::auth::OAuthValidator>) -> Self {
238        self.oauth_validator = Some(validator);
239        self
240    }
241
242    /// Inspect the active OAuth validator, when one is configured.
243    pub fn oauth_validator(&self) -> Option<&Arc<crate::auth::OAuthValidator>> {
244        self.oauth_validator.as_ref()
245    }
246
247    pub fn runtime(&self) -> &RedDBRuntime {
248        &self.runtime
249    }
250
251    pub fn options(&self) -> &GrpcServerOptions {
252        &self.options
253    }
254
255    pub fn auth_store(&self) -> &Arc<AuthStore> {
256        &self.auth_store
257    }
258
259    pub(crate) fn with_listener_options(mut self, options: GrpcServerOptions) -> Self {
260        self.options = options;
261        self
262    }
263
264    fn grpc_runtime(&self) -> GrpcRuntime {
265        GrpcRuntime {
266            runtime: self.runtime.clone(),
267            auth_store: self.auth_store.clone(),
268            prepared_registry: Arc::clone(&self.prepared_registry),
269            oauth_validator: self.oauth_validator.clone(),
270        }
271    }
272
273    pub async fn serve(&self) -> Result<(), Box<dyn std::error::Error>> {
274        let addr = self.options.bind_addr.parse()?;
275        let mut builder = configured_transport_builder();
276        if let Some(tls) = &self.options.tls {
277            // Constant-time SHA256 fingerprint logged for ops triage —
278            // never the bytes of cert/key themselves.
279            log_grpc_tls_identity(tls);
280            builder = builder.tls_config(tls.to_tonic_config()?)?;
281        }
282        builder
283            .add_service(Self::configured_service(self.grpc_runtime()))
284            .serve(addr)
285            .await?;
286        Ok(())
287    }
288
289    pub async fn serve_on(
290        &self,
291        listener: std::net::TcpListener,
292    ) -> Result<(), Box<dyn std::error::Error>> {
293        listener.set_nonblocking(true)?;
294        let listener = tokio::net::TcpListener::from_std(listener)?;
295        let incoming = TcpListenerStream::new(listener);
296        let mut builder = configured_transport_builder();
297        if let Some(tls) = &self.options.tls {
298            log_grpc_tls_identity(tls);
299            builder = builder.tls_config(tls.to_tonic_config()?)?;
300        }
301        builder
302            .add_service(Self::configured_service(self.grpc_runtime()))
303            .serve_with_incoming(incoming)
304            .await?;
305        Ok(())
306    }
307
308    /// Serve gRPC over a stream of already-accepted connections fed by the
309    /// in-process protocol demux (issue #933). The demux classifies each
310    /// inbound connection on the shared port and hands the HTTP/2 ones
311    /// straight in through `rx` — there is no loopback socket and no
312    /// `copy_bidirectional` hop. The server runs until `rx` closes (the
313    /// demux acceptor dropped its sender) and all in-flight RPCs drain.
314    pub(crate) async fn serve_router_demux(
315        &self,
316        rx: tokio::sync::mpsc::Receiver<tokio::net::TcpStream>,
317    ) -> Result<(), Box<dyn std::error::Error>> {
318        use tokio_stream::StreamExt;
319        let incoming = tokio_stream::wrappers::ReceiverStream::new(rx).map(Ok::<_, std::io::Error>);
320        let mut builder = configured_transport_builder();
321        if let Some(tls) = &self.options.tls {
322            log_grpc_tls_identity(tls);
323            builder = builder.tls_config(tls.to_tonic_config()?)?;
324        }
325        builder
326            .add_service(Self::configured_service(self.grpc_runtime()))
327            .serve_with_incoming(incoming)
328            .await?;
329        Ok(())
330    }
331
332    /// Largest gRPC message accepted on the way in or produced on the way
333    /// out. Bulk inserts ride on this, so it is generous, but it is no longer
334    /// 256 MiB: that let one request pin a quarter gigabyte of decoded
335    /// protobuf per stream before any handler ran. Override with
336    /// `REDDB_GRPC_MAX_MESSAGE_BYTES`; a malformed value keeps the default.
337    pub(crate) fn max_message_bytes() -> usize {
338        const DEFAULT: usize = 32 * 1024 * 1024;
339        std::env::var("REDDB_GRPC_MAX_MESSAGE_BYTES")
340            .ok()
341            .and_then(|raw| raw.trim().parse::<usize>().ok())
342            .filter(|value| *value > 0)
343            .unwrap_or(DEFAULT)
344    }
345
346    fn configured_service(runtime: GrpcRuntime) -> GrpcCatalogService {
347        // Advertise zstd + gzip so clients can opt in. Server compresses
348        // outbound replies with zstd; sticking to a single send codec keeps
349        // CPU predictable while still accepting either on inbound.
350        use tonic::codec::CompressionEncoding;
351        let max_message = Self::max_message_bytes();
352        let service = RedDbServer::new(runtime.clone())
353            .max_decoding_message_size(max_message)
354            .max_encoding_message_size(max_message)
355            .accept_compressed(CompressionEncoding::Zstd)
356            .accept_compressed(CompressionEncoding::Gzip)
357            .send_compressed(CompressionEncoding::Zstd);
358        GrpcCatalogService::new(service, runtime)
359    }
360}
361
362#[derive(Clone)]
363struct GrpcRuntime {
364    runtime: RedDBRuntime,
365    auth_store: Arc<AuthStore>,
366    prepared_registry: Arc<PreparedRegistry>,
367    /// OAuth/OIDC JWT validator built once from `auth_store.config().oauth`
368    /// when the operator enables OAuth. `None` means JWT bearers fall
369    /// back to the AuthStore lookup path.
370    oauth_validator: Option<Arc<crate::auth::OAuthValidator>>,
371}
372
373#[derive(Clone)]
374struct ResolvedGrpcAuth {
375    result: AuthResult,
376    identity: Option<(crate::auth::UserId, Role)>,
377}
378
379impl GrpcRuntime {
380    fn admin_use_cases(&self) -> AdminUseCases<'_, RedDBRuntime> {
381        AdminUseCases::new(&self.runtime)
382    }
383
384    fn entity_use_cases(&self) -> EntityUseCases<'_, RedDBRuntime> {
385        EntityUseCases::new(&self.runtime)
386    }
387
388    fn graph_use_cases(&self) -> GraphUseCases<'_, RedDBRuntime> {
389        GraphUseCases::new(&self.runtime)
390    }
391
392    fn native_use_cases(&self) -> NativeUseCases<'_, RedDBRuntime> {
393        NativeUseCases::new(&self.runtime)
394    }
395}
396
397fn grpc_query_value_to_param_value(value: QueryValue) -> Result<ParamValue, Status> {
398    use proto::query_value::Kind;
399
400    match value
401        .kind
402        .ok_or_else(|| Status::invalid_argument("missing query param value"))?
403    {
404        Kind::NullValue(_) => Ok(ParamValue::Null),
405        Kind::BoolValue(value) => Ok(ParamValue::Bool(value)),
406        Kind::IntValue(value) => Ok(ParamValue::Int64(value)),
407        Kind::FloatValue(value) => Ok(ParamValue::Float64(value)),
408        Kind::TextValue(value) => Ok(ParamValue::Text(value)),
409        Kind::BytesValue(value) => Ok(ParamValue::Bytes(value)),
410        Kind::VectorValue(value) => Ok(ParamValue::Vector(value.values)),
411        Kind::JsonValue(value) => {
412            let parsed = json_from_str::<JsonValue>(&value)
413                .map_err(|e| Status::invalid_argument(format!("json param parse error: {e}")))?;
414            let encoded = json_to_string(&parsed)
415                .map_err(|e| Status::invalid_argument(format!("json param encode error: {e}")))?;
416            Ok(ParamValue::Json(encoded.into_bytes()))
417        }
418        Kind::TimestampValue(value) => Ok(ParamValue::Timestamp(value)),
419        Kind::UuidValue(value) => {
420            let bytes: [u8; 16] = value.try_into().map_err(|value: Vec<u8>| {
421                Status::invalid_argument(format!(
422                    "uuid param must be 16 bytes, got {}",
423                    value.len()
424                ))
425            })?;
426            Ok(ParamValue::Uuid(bytes))
427        }
428    }
429}
430
431/// RAII guard scoping the runtime's thread-local identity to one gRPC SQL
432/// call. The catalog interceptor resolves the principal (`tenant/user` or
433/// `user`) but the runtime gates read a thread-local; without installing it
434/// every `Query`/`BatchQuery`/`ExecutePrepared` ran with enforcement off.
435/// The executor is synchronous, so the thread-local holds for the call.
436struct GrpcIdentityGuard {
437    previous_identity: Option<(String, crate::auth::Role)>,
438    previous_principal: Option<crate::auth::UserId>,
439    previous_tenant: Option<String>,
440}
441
442impl GrpcIdentityGuard {
443    fn install(identity: Option<(crate::auth::UserId, crate::auth::Role)>) -> Self {
444        use crate::runtime::execution_context as ctx;
445        let previous_identity = ctx::current_auth_identity_for_audit();
446        let previous_principal = ctx::current_auth_principal();
447        let previous_tenant = ctx::current_tenant();
448        match identity {
449            Some((id, role)) => {
450                match &id.tenant {
451                    Some(tenant) => ctx::set_current_tenant(tenant.clone()),
452                    None => ctx::clear_current_tenant(),
453                }
454                ctx::set_current_auth_principal(id, role);
455            }
456            None => {
457                ctx::clear_current_auth_identity();
458                ctx::clear_current_tenant();
459            }
460        }
461        Self {
462            previous_identity,
463            previous_principal,
464            previous_tenant,
465        }
466    }
467}
468
469impl Drop for GrpcIdentityGuard {
470    fn drop(&mut self) {
471        use crate::runtime::execution_context as ctx;
472        match (
473            self.previous_principal.take(),
474            self.previous_identity.take(),
475        ) {
476            (Some(principal), Some((_, role))) => ctx::set_current_auth_principal(principal, role),
477            _ => ctx::clear_current_auth_identity(),
478        }
479        match self.previous_tenant.take() {
480            Some(tenant) => ctx::set_current_tenant(tenant),
481            None => ctx::clear_current_tenant(),
482        }
483    }
484}
485
486/// Resolve the `(UserId, Role)` a gRPC request executes as from the typed
487/// dispatch context installed by the catalog interceptor.
488fn grpc_request_identity<T>(
489    request: &Request<T>,
490) -> Option<(crate::auth::UserId, crate::auth::Role)> {
491    request
492        .extensions()
493        .get::<catalog_dispatch::GrpcDispatchContext>()
494        .and_then(|context| context.identity.clone())
495}
496
497async fn grpc_spawn_blocking<F, R>(runtime: &RedDBRuntime, f: F) -> Result<R, Status>
498where
499    F: FnOnce() -> R + Send + 'static,
500    R: Send + 'static,
501{
502    use crate::transport::execution_admission::ExecutionAdmissionError;
503
504    let admission = runtime.execution_admission();
505    let permit =
506        match tokio::time::timeout(runtime.execution_queue_timeout(), admission.acquire()).await {
507            Ok(Ok(permit)) => permit,
508            Ok(Err(ExecutionAdmissionError::QueueFull)) => {
509                return Err(Status::resource_exhausted(
510                    "execution_queue_full: engine execution queue is full",
511                ))
512            }
513            Ok(Err(ExecutionAdmissionError::Closed)) => {
514                return Err(Status::unavailable(
515                    "execution_admission_closed: engine execution admission is unavailable",
516                ))
517            }
518            Err(_) => {
519                return Err(Status::deadline_exceeded(
520                    "execution_queue_timeout: deadline expired while waiting to execute",
521                ))
522            }
523        };
524    let bundle = crate::runtime::execution_context::snapshot_bundle();
525    tokio::task::spawn_blocking(move || {
526        let _permit = permit;
527        crate::runtime::execution_context::with_snapshot_bundle(&bundle, f)
528    })
529    .await
530    .map_err(|error| Status::internal(format!("engine execution task failed: {error}")))
531}
532
533fn execute_grpc_query_request(
534    runtime: &RedDBRuntime,
535    prepared: &PreparedRegistry,
536    identity: Option<(crate::auth::UserId, crate::auth::Role)>,
537    query: String,
538    params: Vec<QueryValue>,
539    commit_policy: Option<crate::replication::CommitPolicy>,
540) -> Result<crate::runtime::OwnedQueryResult, Status> {
541    if query.trim().is_empty() {
542        return Err(Status::invalid_argument("query field cannot be empty"));
543    }
544    let _identity = GrpcIdentityGuard::install(identity);
545
546    let params = params
547        .into_iter()
548        .map(grpc_query_value_to_param_value)
549        .collect::<Result<Vec<_>, _>>()?;
550    let mut request = RuntimeQueryRequest::sql(query, params);
551    if let Some(commit_policy) = commit_policy {
552        request = request.with_commit_policy(commit_policy);
553    }
554    QueryRequestExecutor::new(runtime, prepared)
555        .execute(request)
556        .map_err(grpc_query_request_error)
557}
558
559fn grpc_commit_policy_from_metadata(
560    metadata: &MetadataMap,
561) -> Result<Option<crate::replication::CommitPolicy>, Status> {
562    let Some(value) = metadata.get("x-reddb-commit-policy") else {
563        return Ok(None);
564    };
565    let value = value
566        .to_str()
567        .map_err(|_| Status::invalid_argument("x-reddb-commit-policy must be ascii"))?;
568    crate::replication::CommitPolicy::parse_strict(value)
569        .map(Some)
570        .ok_or_else(|| Status::invalid_argument(format!("invalid commit policy '{value}'")))
571}
572
573fn grpc_json_bind_to_param_value(value: &str) -> Result<ParamValue, Status> {
574    let value = json_from_str::<JsonValue>(value)
575        .map_err(|error| Status::invalid_argument(format!("bind parse error: {error}")))?;
576    Ok(match value {
577        JsonValue::Null => ParamValue::Null,
578        JsonValue::Bool(value) => ParamValue::Bool(value),
579        JsonValue::Integer(value) => ParamValue::Int64(value),
580        JsonValue::Number(value) if value.fract() == 0.0 && value.abs() < i64::MAX as f64 => {
581            ParamValue::Int64(value as i64)
582        }
583        JsonValue::Number(value) => ParamValue::Float64(value),
584        JsonValue::String(value) => ParamValue::Text(value),
585        other => ParamValue::Text(json_to_string(&other).unwrap_or_default()),
586    })
587}
588
589fn grpc_query_request_error(error: crate::api::RedDBError) -> Status {
590    let message = error.to_string();
591    if message.contains("commit policy timed out") {
592        return Status::deadline_exceeded(message);
593    }
594    match error {
595        crate::api::RedDBError::Query(message) if message.contains("not found or expired") => {
596            Status::not_found(message)
597        }
598        crate::api::RedDBError::Query(message)
599            if message == "prepared_needs_replan" || message == "prepared statements disabled" =>
600        {
601            Status::failed_precondition(message)
602        }
603        // Client-shaped request errors stay INVALID_ARGUMENT: seam bind
604        // failures and commit-policy floor violations.
605        crate::api::RedDBError::Query(message)
606            if message.contains("prepared bind failed")
607                || message.contains("weaker than resolved floor") =>
608        {
609            Status::invalid_argument(message)
610        }
611        crate::api::RedDBError::Validation { message, .. } => Status::invalid_argument(message),
612        // Everything else keeps the pre-migration status surface: to_status
613        // routes the ask_primary_sync_unavailable prefix to UNAVAILABLE and
614        // generic Query errors to INTERNAL.
615        other => to_status(other),
616    }
617}
618
619#[cfg(test)]
620mod grpc_query_value_tests {
621    use super::*;
622    use proto::query_value::Kind;
623
624    fn mutation_field(name: &str, kind: Kind) -> proto::MutationField {
625        proto::MutationField {
626            name: name.to_string(),
627            value: Some(QueryValue { kind: Some(kind) }),
628        }
629    }
630
631    #[tokio::test]
632    async fn grpc_execution_refuses_when_shared_runtime_queue_is_full() {
633        let runtime =
634            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
635        runtime.configure_execution_admission(1, 0, 100);
636        let admission = runtime.execution_admission();
637        let active = admission.acquire().await.expect("active slot");
638
639        let status = grpc_spawn_blocking(&runtime, || ()).await.unwrap_err();
640        assert_eq!(status.code(), tonic::Code::ResourceExhausted);
641        assert!(status.message().contains("execution_queue_full"));
642        drop(active);
643    }
644
645    #[tokio::test]
646    async fn grpc_execution_reports_queue_deadline_separately() {
647        let runtime =
648            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
649        runtime.configure_execution_admission(1, 1, 1);
650        let admission = runtime.execution_admission();
651        let active = admission.acquire().await.expect("active slot");
652
653        let status = grpc_spawn_blocking(&runtime, || ()).await.unwrap_err();
654        assert_eq!(status.code(), tonic::Code::DeadlineExceeded);
655        assert!(status.message().contains("execution_queue_timeout"));
656        drop(active);
657    }
658
659    #[test]
660    fn grpc_query_value_maps_to_request_param_variants() {
661        let cases = vec![
662            (
663                QueryValue {
664                    kind: Some(Kind::NullValue(proto::QueryNull {})),
665                },
666                ParamValue::Null,
667            ),
668            (
669                QueryValue {
670                    kind: Some(Kind::BoolValue(true)),
671                },
672                ParamValue::Bool(true),
673            ),
674            (
675                QueryValue {
676                    kind: Some(Kind::IntValue(42)),
677                },
678                ParamValue::Int64(42),
679            ),
680            (
681                QueryValue {
682                    kind: Some(Kind::FloatValue(1.5)),
683                },
684                ParamValue::Float64(1.5),
685            ),
686            (
687                QueryValue {
688                    kind: Some(Kind::BytesValue(vec![0, 1, 2])),
689                },
690                ParamValue::Bytes(vec![0, 1, 2]),
691            ),
692            (
693                QueryValue {
694                    kind: Some(Kind::VectorValue(proto::QueryVector {
695                        values: vec![0.25, 0.5],
696                    })),
697                },
698                ParamValue::Vector(vec![0.25, 0.5]),
699            ),
700            (
701                QueryValue {
702                    kind: Some(Kind::TimestampValue(1_779_999_000)),
703                },
704                ParamValue::Timestamp(1_779_999_000),
705            ),
706            (
707                QueryValue {
708                    kind: Some(Kind::UuidValue(vec![0x11; 16])),
709                },
710                ParamValue::Uuid([0x11; 16]),
711            ),
712        ];
713
714        for (input, expected) in cases {
715            assert_eq!(grpc_query_value_to_param_value(input).unwrap(), expected);
716        }
717
718        assert_eq!(
719            grpc_query_value_to_param_value(QueryValue {
720                kind: Some(Kind::TextValue("alice".into())),
721            })
722            .unwrap(),
723            ParamValue::Text("alice".to_string())
724        );
725        assert_eq!(
726            grpc_query_value_to_param_value(QueryValue {
727                kind: Some(Kind::JsonValue("{\"role\":\"admin\"}".into())),
728            })
729            .unwrap(),
730            ParamValue::Json(b"{\"role\":\"admin\"}".to_vec())
731        );
732    }
733
734    #[test]
735    fn grpc_query_value_rejects_missing_kind_and_bad_uuid() {
736        assert!(grpc_query_value_to_param_value(QueryValue { kind: None }).is_err());
737        assert!(grpc_query_value_to_param_value(QueryValue {
738            kind: Some(Kind::UuidValue(vec![0; 15])),
739        })
740        .is_err());
741    }
742
743    #[test]
744    fn grpc_query_rejects_empty_query_before_runtime_parse() {
745        let runtime =
746            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
747        let prepared = PreparedRegistry::new();
748        let err = execute_grpc_query_request(
749            &runtime,
750            &prepared,
751            None,
752            "  ".to_string(),
753            Vec::new(),
754            None,
755        )
756        .expect_err("empty query should fail");
757
758        assert_eq!(err.code(), tonic::Code::InvalidArgument);
759        assert_eq!(err.message(), "query field cannot be empty");
760    }
761
762    #[test]
763    fn grpc_query_params_are_bound_before_execution() {
764        let runtime =
765            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
766        seed_grpc_param_table(&runtime);
767        let prepared = PreparedRegistry::new();
768
769        let result = execute_grpc_query_request(
770            &runtime,
771            &prepared,
772            None,
773            "SELECT id, name FROM p WHERE id = $1 AND name = $2".to_string(),
774            grpc_param_values(),
775            None,
776        )
777        .expect("parameterized query");
778
779        assert_eq!(result.result.records.len(), 1);
780    }
781
782    #[test]
783    fn grpc_query_enforces_ack_n_commit_policy_fail_closed() {
784        let _env_lock = env_lock().lock().expect("env lock");
785        let _env = EnvGuard::set(&[
786            ("RED_PRIMARY_COMMIT_POLICY", "ack_n=1"),
787            ("RED_REPLICATION_ACK_TIMEOUT_MS", "20"),
788            ("RED_COMMIT_FAIL_ON_TIMEOUT", "false"),
789        ]);
790        let data_path = temp_data_path("grpc_ack_n_timeout");
791        cleanup(&data_path);
792
793        let runtime = RedDBRuntime::with_options(
794            crate::api::RedDBOptions::persistent(&data_path)
795                .with_replication(crate::replication::ReplicationConfig::primary()),
796        )
797        .expect("runtime");
798        let prepared = PreparedRegistry::new();
799
800        let err = execute_grpc_query_request(
801            &runtime,
802            &prepared,
803            None,
804            "INSERT INTO grpc_ack_items (id, name) VALUES (1, 'alpha')".to_string(),
805            Vec::new(),
806            None,
807        )
808        .expect_err("ack_n without replica ack must fail closed");
809
810        assert_eq!(err.code(), tonic::Code::DeadlineExceeded);
811        assert!(
812            err.message().contains("commit policy timed out")
813                && err.message().contains("local commit is durable"),
814            "error should identify commit policy timeout, got {err:?}"
815        );
816        assert!(
817            runtime.cdc_current_lsn() > 0,
818            "local mutation should advance CDC before gRPC response fails"
819        );
820
821        cleanup(&data_path);
822    }
823
824    #[tokio::test]
825    async fn grpc_query_rpc_binds_query_request_params() {
826        let runtime =
827            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
828        seed_grpc_param_table(&runtime);
829        let service = GrpcRuntime {
830            runtime,
831            auth_store: Arc::new(AuthStore::new(crate::auth::AuthConfig::default())),
832            prepared_registry: Arc::new(PreparedRegistry::new()),
833            oauth_validator: None,
834        };
835
836        let reply = RedDb::query(
837            &service,
838            Request::new(QueryRequest {
839                query: "SELECT id, name FROM p WHERE id = $1 AND name = $2".to_string(),
840                entity_types: Vec::new(),
841                capabilities: Vec::new(),
842                params: grpc_param_values(),
843            }),
844        )
845        .await
846        .expect("query rpc")
847        .into_inner();
848
849        assert_eq!(reply.record_count, 1);
850        assert!(reply.result_json.contains("Alice"), "{}", reply.result_json);
851        assert!(!reply.result_json.contains("Bob"), "{}", reply.result_json);
852    }
853
854    #[tokio::test]
855    async fn grpc_typed_create_row_preserves_types_and_uses_contract_defaults() {
856        let runtime =
857            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
858        runtime
859            .execute_query(
860                "CREATE TABLE typed_users (id INTEGER PRIMARY KEY, name TEXT NOT NULL, active BOOLEAN DEFAULT = true)",
861            )
862            .expect("create typed table");
863        let service = RedDBGrpcServer::new(runtime.clone()).grpc_runtime();
864
865        let reply = RedDb::create_row_typed(
866            &service,
867            Request::new(TypedCreateRowRequest {
868                collection: "typed_users".to_string(),
869                fields: vec![
870                    mutation_field("id", Kind::IntValue(7)),
871                    mutation_field("name", Kind::TextValue("Ada".to_string())),
872                ],
873            }),
874        )
875        .await
876        .expect("typed insert")
877        .into_inner();
878
879        assert!(reply.ok);
880        let selected = runtime
881            .execute_query("SELECT id, name, active FROM typed_users WHERE id = 7")
882            .expect("select typed row");
883        assert_eq!(selected.result.records.len(), 1);
884        assert_eq!(
885            selected.result.records[0].get("id"),
886            Some(&Value::Integer(7))
887        );
888        assert_eq!(
889            selected.result.records[0].get("name"),
890            Some(&Value::text("Ada"))
891        );
892        assert_eq!(
893            selected.result.records[0].get("active"),
894            Some(&Value::Boolean(true))
895        );
896    }
897
898    #[tokio::test]
899    async fn grpc_typed_create_row_rejects_ambiguous_or_invalid_fields_before_write() {
900        let runtime =
901            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
902        runtime
903            .execute_query(
904                "CREATE TABLE typed_rejects (id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
905            )
906            .expect("create typed table");
907        let service = RedDBGrpcServer::new(runtime.clone()).grpc_runtime();
908
909        let duplicate = RedDb::create_row_typed(
910            &service,
911            Request::new(TypedCreateRowRequest {
912                collection: "typed_rejects".to_string(),
913                fields: vec![
914                    mutation_field("id", Kind::IntValue(1)),
915                    mutation_field("id", Kind::IntValue(2)),
916                    mutation_field("name", Kind::TextValue("Ada".to_string())),
917                ],
918            }),
919        )
920        .await
921        .expect_err("duplicate field must fail");
922        assert_eq!(duplicate.code(), tonic::Code::InvalidArgument);
923        assert!(duplicate.message().contains("duplicate field 'id'"));
924
925        let missing_kind = RedDb::create_row_typed(
926            &service,
927            Request::new(TypedCreateRowRequest {
928                collection: "typed_rejects".to_string(),
929                fields: vec![proto::MutationField {
930                    name: "id".to_string(),
931                    value: Some(QueryValue { kind: None }),
932                }],
933            }),
934        )
935        .await
936        .expect_err("missing value kind must fail");
937        assert_eq!(missing_kind.code(), tonic::Code::InvalidArgument);
938
939        let selected = runtime
940            .execute_query("SELECT id FROM typed_rejects")
941            .expect("select after rejected inserts");
942        assert!(selected.result.records.is_empty());
943    }
944
945    #[tokio::test]
946    async fn grpc_prepared_id_is_shared_by_connection_listeners_only() {
947        let runtime =
948            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
949        let server = RedDBGrpcServer::new(runtime.clone());
950        let plain_listener = server.grpc_runtime();
951        let tls_listener = server.grpc_runtime();
952        let second_connection = RedDBGrpcServer::new(runtime).grpc_runtime();
953
954        let prepared = RedDb::prepare_query(
955            &plain_listener,
956            Request::new(PrepareQueryRequest {
957                query: "SELECT 7 AS value".to_string(),
958            }),
959        )
960        .await
961        .expect("prepare on plaintext listener")
962        .into_inner();
963
964        let reply = RedDb::execute_prepared(
965            &tls_listener,
966            Request::new(ExecutePreparedRequest {
967                prepared_id: prepared.prepared_id,
968                bind_json: vec!["42".to_string()],
969            }),
970        )
971        .await
972        .expect("execute on TLS listener of the same connection")
973        .into_inner();
974        assert!(reply.result_json.contains("42"), "{}", reply.result_json);
975
976        let error = RedDb::execute_prepared(
977            &second_connection,
978            Request::new(ExecutePreparedRequest {
979                prepared_id: prepared.prepared_id,
980                bind_json: vec!["42".to_string()],
981            }),
982        )
983        .await
984        .expect_err("another connection must not resolve the prepared ID");
985        assert_eq!(error.code(), tonic::Code::NotFound);
986    }
987
988    #[tokio::test]
989    async fn grpc_execute_prepared_rejects_a_stale_ddl_epoch() {
990        let runtime =
991            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
992        let service = RedDBGrpcServer::new(runtime.clone()).grpc_runtime();
993        let prepared = RedDb::prepare_query(
994            &service,
995            Request::new(PrepareQueryRequest {
996                query: "SELECT 7 AS value".to_string(),
997            }),
998        )
999        .await
1000        .expect("prepare query")
1001        .into_inner();
1002
1003        runtime
1004            .execute_query("CREATE TABLE grpc_prepared_epoch (id INTEGER)")
1005            .expect("execute DDL");
1006
1007        let error = RedDb::execute_prepared(
1008            &service,
1009            Request::new(ExecutePreparedRequest {
1010                prepared_id: prepared.prepared_id,
1011                bind_json: vec!["42".to_string()],
1012            }),
1013        )
1014        .await
1015        .expect_err("DDL must invalidate the gRPC prepared shape");
1016        assert_eq!(error.code(), tonic::Code::FailedPrecondition);
1017        assert_eq!(error.message(), "prepared_needs_replan");
1018    }
1019
1020    #[tokio::test]
1021    async fn grpc_prepared_kill_switch_rejects_prepare_and_execute() {
1022        let runtime =
1023            RedDBRuntime::with_options(crate::api::RedDBOptions::in_memory()).expect("runtime");
1024        let service = RedDBGrpcServer::new(runtime).grpc_runtime();
1025        let prepared = RedDb::prepare_query(
1026            &service,
1027            Request::new(PrepareQueryRequest {
1028                query: "SELECT 7 AS value".to_string(),
1029            }),
1030        )
1031        .await
1032        .expect("prepare before kill switch")
1033        .into_inner();
1034
1035        service.prepared_registry.disable();
1036
1037        let prepare_error = RedDb::prepare_query(
1038            &service,
1039            Request::new(PrepareQueryRequest {
1040                query: "SELECT 1".to_string(),
1041            }),
1042        )
1043        .await
1044        .expect_err("kill switch must reject prepare");
1045        assert_eq!(prepare_error.code(), tonic::Code::FailedPrecondition);
1046        assert_eq!(prepare_error.message(), "prepared statements disabled");
1047
1048        let execute_error = RedDb::execute_prepared(
1049            &service,
1050            Request::new(ExecutePreparedRequest {
1051                prepared_id: prepared.prepared_id,
1052                bind_json: vec!["42".to_string()],
1053            }),
1054        )
1055        .await
1056        .expect_err("kill switch must reject execute");
1057        assert_eq!(execute_error.code(), tonic::Code::FailedPrecondition);
1058        assert_eq!(execute_error.message(), "prepared statements disabled");
1059    }
1060
1061    #[tokio::test]
1062    async fn grpc_query_honors_per_request_commit_policy() {
1063        let _env_lock = env_lock().lock().expect("env lock");
1064        let _env = EnvGuard::set(&[("RED_PRIMARY_COMMIT_POLICY", "ack_n=1")]);
1065        let runtime = RedDBRuntime::with_options(
1066            crate::api::RedDBOptions::in_memory()
1067                .with_replication(crate::replication::ReplicationConfig::primary()),
1068        )
1069        .expect("runtime");
1070        runtime
1071            .execute_query("CREATE TABLE grpc_request_policy (id INTEGER)")
1072            .expect("create table");
1073        let service = RedDBGrpcServer::new(runtime.clone()).grpc_runtime();
1074        let mut request = Request::new(QueryRequest {
1075            query: "INSERT INTO grpc_request_policy (id) VALUES (1)".to_string(),
1076            entity_types: Vec::new(),
1077            capabilities: Vec::new(),
1078            params: Vec::new(),
1079        });
1080        request
1081            .metadata_mut()
1082            .insert("x-reddb-commit-policy", "local".parse().expect("metadata"));
1083
1084        let error = RedDb::query(&service, request)
1085            .await
1086            .expect_err("weaker per-request policy must fail before mutation");
1087        assert_eq!(error.code(), tonic::Code::InvalidArgument);
1088        assert!(error.message().contains("weaker than resolved floor"));
1089
1090        let rows = runtime
1091            .execute_query("SELECT id FROM grpc_request_policy")
1092            .expect("read rows");
1093        assert!(rows.result.records.is_empty());
1094    }
1095
1096    #[tokio::test]
1097    async fn pull_wal_records_rejects_stale_term_on_grpc_path() {
1098        let runtime = RedDBRuntime::with_options(
1099            crate::api::RedDBOptions::in_memory()
1100                .with_replication(crate::replication::ReplicationConfig::primary().with_term(6)),
1101        )
1102        .expect("runtime");
1103        let auth_store = Arc::new(AuthStore::new(crate::auth::AuthConfig {
1104            enabled: true,
1105            require_auth: true,
1106            ..crate::auth::AuthConfig::default()
1107        }));
1108        let bootstrap = auth_store
1109            .bootstrap("replica", "secret")
1110            .expect("bootstrap");
1111        let policy = crate::auth::policies::Policy::from_json_str(
1112            r#"{
1113                "id": "replication-stream",
1114                "version": 1,
1115                "statements": [{
1116                    "effect": "allow",
1117                    "actions": ["cluster:replication:stream"],
1118                    "resources": ["cluster:replication"]
1119                }]
1120            }"#,
1121        )
1122        .expect("policy");
1123        auth_store.put_policy(policy).expect("install policy");
1124        auth_store
1125            .attach_policy(
1126                crate::auth::store::PrincipalRef::User(crate::auth::UserId::platform("replica")),
1127                "replication-stream",
1128            )
1129            .expect("attach policy");
1130        let service = GrpcRuntime {
1131            runtime,
1132            auth_store,
1133            prepared_registry: Arc::new(PreparedRegistry::new()),
1134            oauth_validator: None,
1135        };
1136
1137        let open = reddb_wire::replication::WalStreamOpen {
1138            since_lsn: 0,
1139            max_count: 1,
1140            replica_id: Some("replica-a".to_string()),
1141            installed_snapshot_token: None,
1142            term: 5,
1143            await_data: false,
1144            await_timeout_ms: 1,
1145        };
1146        let mut request = Request::new(JsonPayloadRequest {
1147            payload_json: String::from_utf8(open.encode_json()).expect("json"),
1148        });
1149        request.metadata_mut().insert(
1150            "authorization",
1151            format!("Bearer {}", bootstrap.api_key.key)
1152                .parse()
1153                .expect("metadata"),
1154        );
1155
1156        let err = RedDb::pull_wal_records(&service, request)
1157            .await
1158            .expect_err("stale term should be fenced");
1159
1160        assert_eq!(err.code(), tonic::Code::FailedPrecondition);
1161        assert!(
1162            err.message().contains("stale")
1163                || err.message().contains("fenced")
1164                || err.message().contains("current term"),
1165            "unexpected stale-term error: {err:?}"
1166        );
1167    }
1168
1169    fn seed_grpc_param_table(runtime: &RedDBRuntime) {
1170        runtime
1171            .execute_query("CREATE TABLE p (id INTEGER, name TEXT)")
1172            .expect("create table");
1173        runtime
1174            .execute_query("INSERT INTO p (id, name) VALUES (1, 'Alice')")
1175            .expect("insert alice");
1176        runtime
1177            .execute_query("INSERT INTO p (id, name) VALUES (2, 'Bob')")
1178            .expect("insert bob");
1179    }
1180
1181    fn grpc_param_values() -> Vec<QueryValue> {
1182        vec![
1183            QueryValue {
1184                kind: Some(Kind::IntValue(1)),
1185            },
1186            QueryValue {
1187                kind: Some(Kind::TextValue("Alice".to_string())),
1188            },
1189        ]
1190    }
1191
1192    fn env_lock() -> &'static std::sync::Mutex<()> {
1193        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
1194        LOCK.get_or_init(|| std::sync::Mutex::new(()))
1195    }
1196
1197    struct EnvGuard {
1198        previous: Vec<(&'static str, Option<String>)>,
1199    }
1200
1201    impl EnvGuard {
1202        fn set(vars: &[(&'static str, &'static str)]) -> Self {
1203            let previous = vars
1204                .iter()
1205                .map(|(key, _)| (*key, std::env::var(key).ok()))
1206                .collect();
1207            for (key, value) in vars {
1208                std::env::set_var(key, value);
1209            }
1210            Self { previous }
1211        }
1212    }
1213
1214    impl Drop for EnvGuard {
1215        fn drop(&mut self) {
1216            for (key, value) in self.previous.iter().rev() {
1217                match value {
1218                    Some(value) => std::env::set_var(key, value),
1219                    None => std::env::remove_var(key),
1220                }
1221            }
1222        }
1223    }
1224
1225    fn temp_data_path(name: &str) -> std::path::PathBuf {
1226        let suffix = SystemTime::now()
1227            .duration_since(UNIX_EPOCH)
1228            .unwrap()
1229            .as_nanos();
1230        std::env::temp_dir().join(format!("reddb_{name}_{suffix}.rdb"))
1231    }
1232
1233    fn cleanup(data_path: &std::path::Path) {
1234        let _ = std::fs::remove_file(data_path);
1235        let _ = std::fs::remove_file(
1236            crate::replication::primary::PrimaryReplication::slot_path_for(data_path),
1237        );
1238        let _ = std::fs::remove_file(crate::replication::primary::LogicalWalSpool::path_for(
1239            data_path,
1240        ));
1241        let _ = std::fs::remove_dir_all(
1242            crate::replication::primary::PrimaryReplication::primary_replica_root_for(data_path),
1243        );
1244        reddb_file::cleanup_rebootstrap_artifacts(data_path);
1245    }
1246}
1247
1248#[cfg(test)]
1249mod grpc_ask_query_reply_tests {
1250    use super::*;
1251    use crate::storage::query::unified::{UnifiedRecord, UnifiedResult};
1252    use reddb_rql::modes::QueryMode;
1253    use reddb_types::Value as SchemaValue;
1254
1255    fn ask_runtime_result() -> RuntimeQueryResult {
1256        let mut result = UnifiedResult::with_columns(vec![
1257            "answer".into(),
1258            "provider".into(),
1259            "model".into(),
1260            "mode".into(),
1261            "retry_count".into(),
1262            "prompt_tokens".into(),
1263            "completion_tokens".into(),
1264            "sources_flat".into(),
1265            "citations".into(),
1266            "validation".into(),
1267        ]);
1268        let mut record = UnifiedRecord::new();
1269        record.set("answer", SchemaValue::text("Deploy failed [^1]."));
1270        record.set("provider", SchemaValue::text("openai"));
1271        record.set("model", SchemaValue::text("gpt-4o-mini"));
1272        record.set("mode", SchemaValue::text("strict"));
1273        record.set("retry_count", SchemaValue::Integer(0));
1274        record.set("prompt_tokens", SchemaValue::Integer(11));
1275        record.set("completion_tokens", SchemaValue::Integer(7));
1276        record.set(
1277            "sources_flat",
1278            SchemaValue::Json(
1279                br#"[{"urn":"urn:reddb:row:deployments:1","kind":"row","collection":"deployments","id":"1"}]"#.to_vec(),
1280            ),
1281        );
1282        record.set(
1283            "citations",
1284            SchemaValue::Json(br#"[{"marker":1,"urn":"urn:reddb:row:deployments:1"}]"#.to_vec()),
1285        );
1286        record.set(
1287            "validation",
1288            SchemaValue::Json(br#"{"ok":true,"warnings":[],"errors":[]}"#.to_vec()),
1289        );
1290        result.push(record);
1291
1292        RuntimeQueryResult {
1293            query: "ASK 'why did deploy fail?'".to_string(),
1294            mode: QueryMode::Sql,
1295            statement: "ask",
1296            engine: "runtime-ai",
1297            result,
1298            affected_rows: 0,
1299            statement_type: "select",
1300            bookmark: None,
1301            notice: None,
1302        }
1303    }
1304
1305    #[test]
1306    fn query_reply_ask_result_json_uses_full_canonical_schema() {
1307        let reply = query_reply(ask_runtime_result(), &None, &None);
1308        let json: crate::json::Value =
1309            crate::json::from_str(&reply.result_json).expect("valid ask json");
1310
1311        assert_eq!(
1312            json.get("answer").and_then(crate::json::Value::as_str),
1313            Some("Deploy failed [^1].")
1314        );
1315        assert_eq!(
1316            json.get("cache_hit").and_then(crate::json::Value::as_bool),
1317            Some(false)
1318        );
1319        assert_eq!(
1320            json.get("cost_usd").and_then(crate::json::Value::as_f64),
1321            Some(0.0)
1322        );
1323        assert_eq!(
1324            json.get("mode").and_then(crate::json::Value::as_str),
1325            Some("strict")
1326        );
1327        assert_eq!(
1328            json.get("retry_count").and_then(crate::json::Value::as_u64),
1329            Some(0)
1330        );
1331        assert!(
1332            json.get("records").is_none(),
1333            "ASK must not be row-wrapped: {}",
1334            reply.result_json
1335        );
1336        assert!(
1337            json.get("sources_flat")
1338                .and_then(crate::json::Value::as_array)
1339                .is_some_and(|sources| sources.len() == 1
1340                    && sources[0]
1341                        .get("payload")
1342                        .and_then(crate::json::Value::as_str)
1343                        .is_some()),
1344            "sources_flat must be parsed with payload fallback: {}",
1345            reply.result_json
1346        );
1347        assert!(
1348            json.get("citations")
1349                .and_then(crate::json::Value::as_array)
1350                .is_some_and(|citations| citations.len() == 1),
1351            "citations must be parsed: {}",
1352            reply.result_json
1353        );
1354        assert_eq!(
1355            json.get("validation")
1356                .and_then(|v| v.get("ok"))
1357                .and_then(crate::json::Value::as_bool),
1358            Some(true)
1359        );
1360    }
1361
1362    #[test]
1363    fn query_reply_non_ask_answer_column_keeps_row_shape() {
1364        let mut result = UnifiedResult::with_columns(vec!["answer".into()]);
1365        let mut record = UnifiedRecord::new();
1366        record.set("answer", SchemaValue::text("plain select"));
1367        result.push(record);
1368
1369        let reply = query_reply(
1370            RuntimeQueryResult {
1371                query: "SELECT 'plain select' AS answer".to_string(),
1372                mode: QueryMode::Sql,
1373                statement: "select",
1374                engine: "runtime-sql",
1375                result,
1376                affected_rows: 0,
1377                statement_type: "select",
1378                bookmark: None,
1379                notice: None,
1380            },
1381            &None,
1382            &None,
1383        );
1384        let json: crate::json::Value =
1385            crate::json::from_str(&reply.result_json).expect("valid query json");
1386
1387        assert!(
1388            json.get("records").is_some(),
1389            "non-ASK must stay row-wrapped"
1390        );
1391        assert!(
1392            json.get("answer").is_none(),
1393            "non-ASK must not use ASK envelope"
1394        );
1395    }
1396
1397    #[test]
1398    fn query_reply_non_ask_json_column_preserves_object() {
1399        let mut result = UnifiedResult::with_columns(vec!["value".into()]);
1400        let mut record = UnifiedRecord::new();
1401        record.set(
1402            "value",
1403            SchemaValue::Json(br#"{"alpha":"A","nested":{"leaf":12}}"#.to_vec()),
1404        );
1405        result.push(record);
1406
1407        let reply = query_reply(
1408            RuntimeQueryResult {
1409                query: "LIST KV proj AS JSON".to_string(),
1410                mode: QueryMode::Sql,
1411                statement: "kv_list_json",
1412                engine: "kv",
1413                result,
1414                affected_rows: 0,
1415                statement_type: "select",
1416                bookmark: None,
1417                notice: None,
1418            },
1419            &None,
1420            &None,
1421        );
1422        let json: crate::json::Value =
1423            crate::json::from_str(&reply.result_json).expect("valid query json");
1424        let value = json
1425            .get("records")
1426            .and_then(crate::json::Value::as_array)
1427            .and_then(|records| records.first())
1428            .and_then(|record| record.get("value"))
1429            .expect("value column");
1430
1431        assert_eq!(
1432            value.get("alpha").and_then(crate::json::Value::as_str),
1433            Some("A")
1434        );
1435        assert_eq!(
1436            value
1437                .get("nested")
1438                .and_then(|nested| nested.get("leaf"))
1439                .and_then(crate::json::Value::as_f64),
1440            Some(12.0)
1441        );
1442    }
1443}
1444
1445/// Emit a single info-level event with the SHA-256 fingerprint of the
1446/// active gRPC server cert + an mTLS flag. Never logs PEM bytes.
1447fn log_grpc_tls_identity(tls: &GrpcTlsOptions) {
1448    use sha2::{Digest, Sha256};
1449    let cert_fp = {
1450        let mut h = Sha256::new();
1451        h.update(&tls.cert_pem);
1452        let digest = h.finalize();
1453        // First 16 hex chars are enough for human cross-check; the full
1454        // SHA-256 lives in audit logs only.
1455        let mut buf = String::with_capacity(64);
1456        for b in digest.iter() {
1457            buf.push_str(&format!("{b:02x}"));
1458        }
1459        buf
1460    };
1461    tracing::info!(
1462        target: "reddb::security",
1463        transport = "grpc",
1464        cert_sha256 = %cert_fp,
1465        mtls = tls.client_ca_pem.is_some(),
1466        "gRPC TLS identity loaded"
1467    );
1468}
1469
1470include!("grpc/service_impl.rs");